字符串示例
one thousand only
two hundred
twenty
seven
我如何改变一个大写字母的字符串的第一个字符,而不改变任何其他字母的情况?
更改之后应该是:
One thousand only
Two hundred
Twenty
Seven
注意:我不想使用apache.commons.lang.WordUtils来做这件事。
字符串示例
one thousand only
two hundred
twenty
seven
我如何改变一个大写字母的字符串的第一个字符,而不改变任何其他字母的情况?
更改之后应该是:
One thousand only
Two hundred
Twenty
Seven
注意:我不想使用apache.commons.lang.WordUtils来做这件事。
当前回答
1. 使用字符串的substring()方法
public static String capitalize(String str) {
if(str== null || str.isEmpty()) {
return str;
}
return str.substring(0, 1).toUpperCase() + str.substring(1);
}
现在只需调用capitalize()方法将字符串的第一个字母转换为大写字母:
System.out.println(capitalize("stackoverflow")); // Stackoverflow
System.out.println(capitalize("heLLo")); // HeLLo
System.out.println(capitalize(null)); // null
2. Apache Commons Lang
Commons Lang中的StringUtils类提供了capitalize()方法,该方法也可用于此目的:
System.out.println(StringUtils.capitalize("apache commons")); // Apache commons
System.out.println(StringUtils.capitalize("heLLO")); // HeLLO
System.out.println(StringUtils.uncapitalize(null)); // null
将以下依赖项添加到pom.xml文件中(仅适用于Maven):
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
下面是一篇详细解释这两种方法的文章。
其他回答
用StringBuilder解决方案:
value = new StringBuilder()
.append(value.substring(0, 1).toUpperCase())
.append(value.substring(1))
.toString();
. .基于之前的答案
我的函数方法。它在整个段落的白转义后将句子中的第一个字符颠倒。
如果只启用单词的第一个字符,只需删除.split(" ")
b.name.split(" ")
.filter { !it.isEmpty() }
.map { it.substring(0, 1).toUpperCase()
+it.substring(1).toLowerCase() }
.joinToString(" ")
不管你的inputString的值是多少,下面将给你相同的一致输出:
if(StringUtils.isNotBlank(inputString)) {
inputString = StringUtils.capitalize(inputString.toLowerCase());
}
StringUtils.capitalize(str)
来自apache commons-lang。
用这个:
char[] chars = {Character.toUpperCase(A.charAt(0)),
Character.toUpperCase(B.charAt(0))};
String a1 = chars[0] + A.substring(1);
String b1 = chars[1] + B.substring(1);