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

488,260

Solution 1

WordUtils.capitalize(str) (from apache commons-text)

(Note: if you need "fOO BAr" to become "Foo Bar", then use capitalizeFully(..) instead)

Solution 2

If you're only worried about the first letter of the first word being capitalized:

private String capitalize(final String line) {
   return Character.toUpperCase(line.charAt(0)) + line.substring(1);
}

Solution 3

The following method converts all the letters into upper/lower case, depending on their position near a space or other special chars.

public static String capitalizeString(String string) {
  char[] chars = string.toLowerCase().toCharArray();
  boolean found = false;
  for (int i = 0; i < chars.length; i++) {
    if (!found && Character.isLetter(chars[i])) {
      chars[i] = Character.toUpperCase(chars[i]);
      found = true;
    } else if (Character.isWhitespace(chars[i]) || chars[i]=='.' || chars[i]=='\'') { // You can add other chars here
      found = false;
    }
  }
  return String.valueOf(chars);
}

Solution 4

Try this very simple way

example givenString="ram is good boy"

public static String toTitleCase(String givenString) {
    String[] arr = givenString.split(" ");
    StringBuffer sb = new StringBuffer();

    for (int i = 0; i < arr.length; i++) {
        sb.append(Character.toUpperCase(arr[i].charAt(0)))
            .append(arr[i].substring(1)).append(" ");
    }          
    return sb.toString().trim();
}  

Output will be: Ram Is Good Boy

Solution 5

I made a solution in Java 8 that is IMHO more readable.

public String firstLetterCapitalWithSingleSpace(final String words) {
    return Stream.of(words.trim().split("\\s"))
    .filter(word -> word.length() > 0)
    .map(word -> word.substring(0, 1).toUpperCase() + word.substring(1))
    .collect(Collectors.joining(" "));
}

The Gist for this solution can be found here: https://gist.github.com/Hylke1982/166a792313c5e2df9d31

Share:
488,260
WillfulWizard
Author by

WillfulWizard

I graduated U.C. Davis with a BS in CS, now I'm a programmer with a love of web development and databases.

Updated on February 17, 2022

Comments

  • WillfulWizard
    WillfulWizard about 2 years

    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 skeet -> Jon Skeet
    • miles o'Brien -> Miles O'Brien (B remains capital, this rules out Title Case)
    • old mcdonald -> Old Mcdonald*

    *(Old McDonald would be find too, but I don't expect it to be THAT smart.)

    A quick look at the Java String Documentation reveals only toUpperCase() and toLowerCase(), which of course do not provide the desired behavior. Naturally, Google results are dominated by those two functions. It seems like a wheel that must have been invented already, so it couldn't hurt to ask so I can use it in the future.