字符串示例

one thousand only
two hundred
twenty
seven

我如何改变一个大写字母的字符串的第一个字符,而不改变任何其他字母的情况?

更改之后应该是:

One thousand only
Two hundred
Twenty
Seven

注意:我不想使用apache.commons.lang.WordUtils来做这件事。


当前回答

在这里(希望这能让你明白):

/*************************************************************************
 *  Compilation:  javac Capitalize.java
 *  Execution:    java Capitalize < input.txt
 * 
 *  Read in a sequence of words from standard input and capitalize each
 *  one (make first letter uppercase; make rest lowercase).
 *
 *  % java Capitalize
 *  now is the time for all good 
 *  Now Is The Time For All Good 
 *  to be or not to be that is the question
 *  To Be Or Not To Be That Is The Question 
 *
 *  Remark: replace sequence of whitespace with a single space.
 *
 *************************************************************************/

public class Capitalize {

    public static String capitalize(String s) {
        if (s.length() == 0) return s;
        return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
    }

    public static void main(String[] args) {
        while (!StdIn.isEmpty()) {
            String line = StdIn.readLine();
            String[] words = line.split("\\s");
            for (String s : words) {
                StdOut.print(capitalize(s) + " ");
            }
            StdOut.println();
        }
    }

}

其他回答

如果你只想大写一个名为input的字符串的第一个字母,其余的保持不变:

String output = input.substring(0, 1).toUpperCase() + input.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);

用StringBuilder解决方案:

value = new StringBuilder()
                .append(value.substring(0, 1).toUpperCase())
                .append(value.substring(1))
                .toString();

. .基于之前的答案

实际上,在这种情况下,如果避免使用+运算符并使用concat(),您将获得最佳性能。它是合并两个字符串的最佳选择(但不太适合合并很多字符串)。在这种情况下,代码看起来是这样的:

String output = input.substring(0, 1).toUpperCase().concat(input.substring(1));
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;
    }