Java Proper Case

From EggeWiki

Jump to: navigation, 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:

	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();
	}

And here's a basic unit test:

	public void testProperCase() throws Exception {
		assertEquals("Foo Bar", properCase("fOo baR"));
	}

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:

"fOo BAR".downcase.gsub(/\b\w/){$&.upcase}
=> "Foo Bar"
Personal tools
Travelling Salesman

Get the app!