How to capitalize the first character of each word in a string

后端 未结 30 1427
情深已故
情深已故 2020-11-22 02:08

Is there a function built into Java that capitalizes the first character of each word in a String, and does not affect the others?

Examples:

  • jon
30条回答
  •  再見小時候
    2020-11-22 02:26

    There are many way to convert the first letter of the first word being capitalized. I have an idea. It's very simple:

    public String capitalize(String str){
    
         /* The first thing we do is remove whitespace from string */
         String c = str.replaceAll("\\s+", " ");
         String s = c.trim();
         String l = "";
    
         for(int i = 0; i < s.length(); i++){
              if(i == 0){                              /* Uppercase the first letter in strings */
                  l += s.toUpperCase().charAt(i);
                  i++;                                 /* To i = i + 1 because we don't need to add               
                                                        value i = 0 into string l */
              }
    
              l += s.charAt(i);
    
              if(s.charAt(i) == 32){                   /* If we meet whitespace (32 in ASCII Code is whitespace) */
                  l += s.toUpperCase().charAt(i+1);    /* Uppercase the letter after whitespace */
                  i++;                                 /* Yo i = i + 1 because we don't need to add
                                                       value whitespace into string l */
              }        
         }
         return l;
    }
    

提交回复
热议问题