How to capitalize the first letter of word in a string using Java?

前端 未结 25 1170
抹茶落季
抹茶落季 2020-11-27 09:50

Example strings

one thousand only
two hundred
twenty
seven

How do I change the first character of a string in capital letter and not change

相关标签:
25条回答
  • 2020-11-27 10:49

    Simplest way is to use org.apache.commons.lang.StringUtils class

    StringUtils.capitalize(Str);

    0 讨论(0)
  • 2020-11-27 10:49

    You can try the following code:

    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();
    }
    
    0 讨论(0)
  • 2020-11-27 10:51

    Update July 2019

    Currently, the most up-to-date library function for doing this is contained in org.apache.commons.lang3.StringUtils

    import org.apache.commons.lang3.StringUtils;
    
    StringUtils.capitalize(myString);
    

    If you're using Maven, import the dependency in your pom.xml:

    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
      <version>3.9</version>
    </dependency>
    
    0 讨论(0)
  • 2020-11-27 10:54
    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;
        }
    
    0 讨论(0)
  • 2020-11-27 10:54

    Use this:

    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);
    
    0 讨论(0)
  • 2020-11-27 10:55

    StringUtils.capitalize(str)

    from apache commons-lang.

    0 讨论(0)
提交回复
热议问题