Java中,转换一个英文字符串,使用合适的方式转换,比如首字母大写,其它小写。或者是一个单词的组合,如“”“helloworld”,使用什么方法可以转换为“”“HelloWorld”
时间: 2024-05-02 12:17:38 浏览: 98
可以使用Java中的String类的相关方法来实现字符串转换的功能。
1. 首字母大写,其它小写
可以使用String类的toLowerCase()方法和toUpperCase()方法将字符串转换为小写和大写,再使用substring()方法截取首字母并转换为大写,最后使用+运算符将首字母和其它字符拼接起来即可。
示例代码:
```
public static String capitalize(String str) {
if (str == null || str.isEmpty()) {
return str;
}
return str.substring(0, 1).toUpperCase() + str.substring(1).toLowerCase();
}
```
2. 单词组合,首字母大写
可以使用String类的split()方法将字符串按照指定的分隔符拆分成单词数组,再使用substring()方法截取单词的首字母并转换为大写,最后使用+运算符将单词拼接起来即可。
示例代码:
```
public static String toCamelCase(String str) {
if (str == null || str.isEmpty()) {
return str;
}
String[] words = str.split("_");
StringBuilder sb = new StringBuilder();
for (String word : words) {
sb.append(word.substring(0, 1).toUpperCase()).append(word.substring(1));
}
return sb.toString();
}
```
以上两种方法可以根据具体需求进行调整,例如可以添加参数来指定分隔符等。
阅读全文
相关推荐
















