Java Proper Case: Difference between revisions

From EggeWiki
m (New page: 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 bit...)
 
mNo edit summary
Line 25: Line 25:


You'll want to make the Pattern static if you anticipate calling this function a number of times.   
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>


[[Category:Java|Proper Case]]
[[Category:Java|Proper Case]]
[[Category:Ruby|Proper Case]]

Revision as of 21:05, 16 September 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>