Java Proper Case: Difference between revisions

From EggeWiki
mNo edit summary
mNo edit summary
 
Line 35: Line 35:
[[Category:Java|Proper Case]]
[[Category:Java|Proper Case]]
[[Category:Ruby|Proper Case]]
[[Category:Ruby|Proper Case]]
[[Category:Regex|Proper Case]]

Latest revision as of 20:19, 18 October 2009

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>