Java to Capitalize the First Letter of Each Word in a Sentence

| No TrackBacks
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();

}

Or, you could avoid writing custom code all together and use something like org.apache.commons.lang.WordUtils.capitalize().

Enjoy.

Did You Find this Helpful?

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

  

Send Mark a Direct Message

If you'd like to send me a direct message, please do so below. However, I do not publicly post comments or messages submitted directly to me. So, if you're going to try to SPAM me, or my blog, you're pretty much wasting your time.

400 characters remaining

Error

About Mark

A Silicon Valley native, Mark Kolich is a full-time Software Engineer, a casual entrepreneur, and a consultant for hire. A web technologies expert, his current focus is on building powerful and robust cloud-driven web-applications using Java, PHP, Perl, AJAX, DHTML, CSS, and JavaScript. His favorite programming languages are PHP, Java and JavaScript. He uses Linux, enjoys biking to work, loves building great software, and always writes elegant, readable, and maintainable code.

No TrackBacks

No trackbacks attached to this entry.

Twitter (@markkolich)

Translate

About this Entry

This page contains a single entry by Mark Kolich published on April 21, 2009 10:55 PM.

HOWTO: Set expose_php=Off in php.ini To Hide PHP Version in HTTP Headers (X-Powered-By) was the previous entry in this blog.

PHP's Object Notation: Accessing Fields/Members With Hyphens in Their Name is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.