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

前端 未结 25 1082
抹茶落季
抹茶落季 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:37
    public String capitalizeFirstLetter(String original) {
        if (original == null || original.length() == 0) {
            return original;
        }
        return original.substring(0, 1).toUpperCase() + original.substring(1);
    }
    

    Just... a complete solution, I see it kind of just ended up combining what everyone else ended up posting =P.

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

    Its simple only one line code is needed for this. if String A = scanner.nextLine(); then you need to write this to display the string with this first letter capitalized.

    System.out.println(A.substring(0, 1).toUpperCase() + A.substring(1));

    And its done now.

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

    My functional approach. its capstilise first character in sentence after whitescape in whole paragraph.

    For capatilising only first character of the word just remove .split(" ")

               b.name.split(" ")
                     .filter { !it.isEmpty() }
                     .map { it.substring(0, 1).toUpperCase() 
                     +it.substring(1).toLowerCase() }
                      .joinToString(" ")
    
    0 讨论(0)
  • 2020-11-27 10:43

    Given the input string:

    Character.toUpperCase(input.charAt(0)) + input.substring(1).toLowerCase()
    
    0 讨论(0)
  • 2020-11-27 10:44

    The following will give you the same consistent output regardless of the value of your inputString:

    if(StringUtils.isNotBlank(inputString)) {
        inputString = StringUtils.capitalize(inputString.toLowerCase());
    }
    
    0 讨论(0)
提交回复
热议问题