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