字符串示例
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来做这件事。
当前回答
我的函数方法。它在整个段落的白转义后将句子中的第一个字符颠倒。
如果只启用单词的第一个字符,只需删除.split(" ")
b.name.split(" ")
.filter { !it.isEmpty() }
.map { it.substring(0, 1).toUpperCase()
+it.substring(1).toLowerCase() }
.joinToString(" ")
其他回答
您可以尝试以下代码:
public string capitalize(str) {
String[] array = str.split(" ");
String newStr;
for(int i = 0; i < array.length; i++) {
newStr += array[i].substring(0,1).toUpperCase() + array[i].substring(1) + " ";
}
return newStr.trim();
}
另外,Spring Framework中还有org.springframework.util.StringUtils:
StringUtils.capitalize(str);
2019年7月更新
目前,用于实现此功能的最新库函数包含在 org.apache.commons.lang3.StringUtils
import org.apache.commons.lang3.StringUtils;
StringUtils.capitalize(myString);
如果你正在使用Maven,在pom.xml中导入依赖项:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
把所有的东西加在一起,在字符串的开头修剪出额外的空白是一个好主意。否则,.substring(0, 1)。toUpperCase将尝试大写一个空白。
public String capitalizeFirstLetter(String original) {
if (original == null || original.length() == 0) {
return original;
}
return original.trim().substring(0, 1).toUpperCase() + original.substring(1);
}
给定输入字符串:
Character.toUpperCase(input.charAt(0)) + input.substring(1).toLowerCase()