views:

2028

answers:

3

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. Just 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. Thanks!

+1  A: 

Did you mean Title case?

Shoban
Close, but not exactly. I don't want the letters after the first to be changed. Title case enforces that the other letters are set to Lower.
Willfulwizard
+9  A: 

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

Bozho
I think you mean WordUtils.capitalize(str). See API for details.
Hans Doggen
yeah. StringUtils also has it, but for one-word strings. Thanks.
Bozho
Keeping my philosophy of always voting up answers that refer to the commons libraries.
Ravi Wallau
Yup, code reuse is a sensible policy :)
Bozho
A common library is exactly what I was asking for: debugging (hopefully) done.Still would love to see a function that doesn't require a download separate from the JDK, but this is everything else I was looking for. Thank you!
Willfulwizard
+3  A: 

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);
}
True Soft
Doesn't work for surrogate pairs...
Tom Hawtin - tackline