Capitalize the first letter of each word in a string in Java


Topics interesting only for Java programmers

Link to this posting

Postby Ursego » 10 Sep 2019, 06:48

Code: Select all
// Converts the first letter of each word in the given string to upper case, and the rest of the letters to lower case: "aaa BBB cCc" >>> "Aaa Bbb Ccc".
// The words must be separated by a single space.
public static String capitalizeFirstLetterOfEachWord(String givenString) {
   String[] words = givenString.split(" ");
   StringBuffer sb = new StringBuffer();

   for (int i = 0; i < words.length; i++) {
      sb.append(Character.toUpperCase(words[i].charAt(0))); // the first letter - to upper case
      sb.append(words[i].substring(1).toLowerCase()); // the rest of the letters - to lower case
      if (i < (words.length - 1))
         sb.append(" ");
   }
   return sb.toString();
}
User avatar
Ursego
Site Admin
 
Posts: 143
Joined: 19 Feb 2013, 20:33



Ketones are a more high-octane fuel for your brain than glucose. Become a biohacker and upgrade yourself to version 2.0!



cron
Traffic Counter

eXTReMe Tracker