Uppercase first letter of each word

Inspired by this thread, here is a simple solution. Buggy, since it replaces separating whitespaces with only one, and assumes that whitespaces are the only separators between words, but neat enough.

public class UpperFirst {
    public static void main(String[] args) {
        String test = "This is some  test text, indeed a test.";
        String[] words = test.split("[ ]+");

        StringBuffer buffer = new StringBuffer();
        for (String word : words) {
            buffer.append(Character.toUpperCase(word.charAt(0)));
            if (word.length() > 1) {
                buffer.append(word.substring(1).toLowerCase());
            }
            buffer.append(" ");
        }

        System.out.println(buffer);
    }
}

For a less “buggy” solution, I would more than likely go for regular expressions:

public class UpperFirstRegexp {
	public static void main(String[] args) {
		String test = "This is some  test text,indeed, a test.";
		java.util.regex.Pattern p = java.util.regex.Pattern.compile("(\\w+)");
		java.util.regex.Matcher m = p.matcher(test);
		StringBuffer sb = new StringBuffer();
		while (m.find()) {
			StringBuffer s = new StringBuffer();
			s.append(Character.toUpperCase(m.group(1).charAt(0)));
			if (m.group(1).length() > 1) {
				s.append(m.group(1).substring(1).toLowerCase());
			}
			m.appendReplacement(sb, s.toString());
		}
		m.appendTail(sb);
		System.out.println(sb.toString());
	}
}
 
---

Comment

your_ip_is_blacklisted_by sbl.spamhaus.org

---