Java Proper Case

From EggeWiki
Jump to navigation Jump to search

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.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>