编写一个Java程序,实现将给定的字符串中的所有单词首字母大写,并输出结果。例如,字符串"hello world"转换后为"Hello World"
时间: 2024-05-04 21:18:39 浏览: 11
可以使用Java中的split()方法将字符串分割成单词,然后使用substring()方法将每个单词的首字母转换为大写,最后将所有单词拼接起来即可。以下是示例代码:
```
public class Main {
public static void main(String[] args) {
String str = "hello world";
String[] words = str.split(" ");
StringBuilder sb = new StringBuilder();
for (String word : words) {
sb.append(word.substring(0, 1).toUpperCase()).append(word.substring(1)).append(" ");
}
String result = sb.toString().trim();
System.out.println(result);
}
}
```
输出结果为:Hello World
相关问题
python对给定字符串,将字符串中的所有单词的首字母大写
可以使用Python内置的字符串方法title()来实现这个功能。title()方法会将字符串中的每个单词的首字母大写,其余字母小写。
示例代码如下:
```python
s = "hello world"
s = s.title()
print(s)
```
输出结果为:
```
Hello World
```
注意,这个方法会将每个单词的首字母都大写,如果你只想将字符串的第一个单词的首字母大写,可以使用capitalize()方法。
用python实现统计一个给定字符串中,大写字母小写字母数字的个数,并以字典形式返回结果
可以使用以下代码实现:
```python
def count_chars(s):
counts = {'upper': 0, 'lower': 0, 'digit': 0}
for c in s:
if c.isupper():
counts['upper'] += 1
elif c.islower():
counts['lower'] += 1
elif c.isdigit():
counts['digit'] += 1
return counts
```
这个函数接受一个字符串作为参数,然后遍历字符串中的每个字符,统计大写字母、小写字母和数字的个数,并将结果存储在一个字典中,最后返回这个字典。
例如,如果你调用 `count_chars('Hello World 123')`,它会返回 `{'upper': 2, 'lower': 8, 'digit': 3}`,表示这个字符串中有 2 个大写字母、8 个小写字母和 3 个数字。