字符串示例

one thousand only
two hundred
twenty
seven

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

更改之后应该是:

One thousand only
Two hundred
Twenty
Seven

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


当前回答

把所有的东西加在一起,在字符串的开头修剪出额外的空白是一个好主意。否则,.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);
    }

其他回答

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

String output = input.substring(0, 1).toUpperCase().concat(input.substring(1));

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

/*************************************************************************
 *  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();
        }
    }

}

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>

给定输入字符串:

Character.toUpperCase(input.charAt(0)) + input.substring(1).toLowerCase()
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;
    }