字符串示例
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来做这件事。
当前回答
我想在接受的答案上添加一个NULL检查和IndexOutOfBoundsException。
String output = input.substring(0, 1).toUpperCase() + input.substring(1);
Java代码:
class Main {
public static void main(String[] args) {
System.out.println("Capitalize first letter ");
System.out.println("Normal check #1 : ["+ captializeFirstLetter("one thousand only")+"]");
System.out.println("Normal check #2 : ["+ captializeFirstLetter("two hundred")+"]");
System.out.println("Normal check #3 : ["+ captializeFirstLetter("twenty")+"]");
System.out.println("Normal check #4 : ["+ captializeFirstLetter("seven")+"]");
System.out.println("Single letter check : ["+captializeFirstLetter("a")+"]");
System.out.println("IndexOutOfBound check : ["+ captializeFirstLetter("")+"]");
System.out.println("Null Check : ["+ captializeFirstLetter(null)+"]");
}
static String captializeFirstLetter(String input){
if(input!=null && input.length() >0){
input = input.substring(0, 1).toUpperCase() + input.substring(1);
}
return input;
}
}
输出:
Normal check #1 : [One thousand only]
Normal check #2 : [Two hundred]
Normal check #3 : [Twenty]
Normal check #4 : [Seven]
Single letter check : [A]
IndexOutOfBound check : []
Null Check : [null]
其他回答
用这个:
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);
String s=t.getText().trim();
int l=s.length();
char c=Character.toUpperCase(s.charAt(0));
s=c+s.substring(1);
for(int i=1; i<l; i++)
{
if(s.charAt(i)==' ')
{
c=Character.toUpperCase(s.charAt(i+1));
s=s.substring(0, i) + c + s.substring(i+2);
}
}
t.setText(s);
实际上,在这种情况下,如果避免使用+运算符并使用concat(),您将获得最佳性能。它是合并两个字符串的最佳选择(但不太适合合并很多字符串)。在这种情况下,代码看起来是这样的:
String output = input.substring(0, 1).toUpperCase().concat(input.substring(1));
把所有的东西加在一起,在字符串的开头修剪出额外的空白是一个好主意。否则,.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);
}
用StringBuilder解决方案:
value = new StringBuilder()
.append(value.substring(0, 1).toUpperCase())
.append(value.substring(1))
.toString();
. .基于之前的答案