字符串示例
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来做这件事。
当前回答
public static String capitalize(String str){
String[] inputWords = str.split(" ");
String outputWords = "";
for (String word : inputWords){
if (!word.isEmpty()){
outputWords = outputWords + " "+StringUtils.capitalize(word);
}
}
return outputWords;
}
其他回答
String sentence = "ToDAY WeAthEr GREat";
public static String upperCaseWords(String sentence) {
String words[] = sentence.replaceAll("\\s+", " ").trim().split(" ");
String newSentence = "";
for (String word : words) {
for (int i = 0; i < word.length(); i++)
newSentence = newSentence + ((i == 0) ? word.substring(i, i + 1).toUpperCase():
(i != word.length() - 1) ? word.substring(i, i + 1).toLowerCase() : word.substring(i, i + 1).toLowerCase().toLowerCase() + " ");
}
return newSentence;
}
//Today Weather Great
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>
class Test {
public static void main(String[] args) {
String newString="";
String test="Hii lets cheCk for BEING String";
String[] splitString = test.split(" ");
for(int i=0; i<splitString.length; i++){
newString= newString+ splitString[i].substring(0,1).toUpperCase()
+ splitString[i].substring(1,splitString[i].length()).toLowerCase()+" ";
}
System.out.println("the new String is "+newString);
}
}
即使是“简单”的代码,我也会使用库。问题不是代码本身,而是已经存在的覆盖例外情况的测试用例。这可以是null,空字符串,其他语言中的字符串。
文字操作部分已经从Apache Commons Lang中移除。它现在被放置在Apache Commons Text中。通过https://search.maven.org/artifact/org.apache.commons/commons-text获取。
你可以使用WordUtils。大写(字符串str)从Apache公共文本。它比你想要的更强大。它也可以大写full(例如,固定“oNe thousand only”)。
由于它适用于完整的文本,所以必须告诉它只大写第一个单词。
WordUtils.capitalize("one thousand only", new char[0]);
完整的JUnit类,使发挥功能:
package io.github.koppor;
import org.apache.commons.text.WordUtils;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class AppTest {
@Test
void test() {
assertEquals("One thousand only", WordUtils.capitalize("one thousand only", new char[0]));
}
}
不管你的inputString的值是多少,下面将给你相同的一致输出:
if(StringUtils.isNotBlank(inputString)) {
inputString = StringUtils.capitalize(inputString.toLowerCase());
}