I finally bit the bullet, and solved this the introduction-to-programming way, which is to loop through each character in the String, and capitalize the letters that sit at the start of a word-boundary. It makes me shudder when I have to "loop through" letters in a String, but I guess there are some problems that simply cannot be solved without doing just that.
Here's the code:
public static String capitalizeFirstLetters ( String s ) {
for (int i = 0; i < s.length(); i++) {
if (i == 0) {
// Capitalize the first letter of the string.
s = String.format( "%s%s",
Character.toUpperCase(s.charAt(0)),
s.substring(1) );
}
// Is this character a non-letter or non-digit? If so
// then this is probably a word boundary so let's capitalize
// the next character in the sequence.
if (!Character.isLetterOrDigit(s.charAt(i))) {
if (i + 1 < s.length()) {
s = String.format( "%s%s%s",
s.subSequence(0, i+1),
Character.toUpperCase(s.charAt(i + 1)),
s.substring(i+2) );
}
}
}
return s;
}
Note that another solution might involve using a StringTokenizer, like so:
public static String capitalizeFirstLettersTokenizer ( String s ) {
final StringTokenizer st = new StringTokenizer( s, " ", true );
final StringBuilder sb = new StringBuilder();
while ( st.hasMoreTokens() ) {
String token = st.nextToken();
token = String.format( "%s%s",
Character.toUpperCase(token.charAt(0)),
token.substring(1) );
sb.append( token );
}
return sb.toString();
}
Or, you could avoid writing custom code all together and use something like org.apache.commons.lang.WordUtils.capitalize().
Enjoy.


Did you find this post helpful, or at least, interesting?