Java Proper Case

From EggeWiki
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

A quick search on how to proper case or title case a Java string returned a number way to approach this problem. In C/assembly you can do the replacement in place, and very fast using bitmasks.

None of the Java solutions I found used the regular expression library. The Java regex library is quite good IMHO, and I tend to attempt to use it whenever I'm performing string operations. The results are usually faster and more concise than a hand written loop. Here's my function to proper case a string:

<geshi lang="java5"> static String properCase(String s) { Pattern p = Pattern.compile("(^|\\W)([a-z])"); Matcher m = p.matcher(s.toLowerCase()); StringBuffer sb = new StringBuffer(s.length()); while(m.find()) { m.appendReplacement(sb, m.group(1) + m.group(2).toUpperCase() ); } m.appendTail(sb); return sb.toString(); } </geshi>

And here's a basic unit test:

<geshi lang="java5"> public void testProperCase() throws Exception { assertEquals("Foo Bar", properCase("fOo baR")); } </geshi>

You'll want to make the Pattern static if you anticipate calling this function a number of times.

In Ruby, you can do the same thing like this:

<geshi lang="ruby"> "fOo BAR".downcase.gsub(/\b\w/){$&.upcase} => "Foo Bar" </geshi>