Every once in a while, I find myself stuck on the most mundane and boring coding problems. Take this one, for example:
use Java to capitalize the first letter of each word in a sentence. Amazingly, I actually had a need today to write some Java code that does just that. Sounds trivial; I actually ended up spending almost half-an-hour on this (I know, you can laugh at me, but I just couldn't wrap my head around this one). My first reaction was to use a regular expression, but I realized that, unlike Perl, Java doesn't support
\u which can come in handy when capitalizing letters in a regex. From what I read online, there are quite a few back references and other escape sequences built into Perl regular expressions that Java doesn't support.
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();
}
Enjoy.