How to upper case every first letter of word in a string?

Viewed 307534

I have a string: "hello good old world" and i want to upper case every first letter of every word, not the whole string with .toUpperCase(). Is there an existing java helper which does the job?

16 Answers

Have a look at ACL WordUtils.

WordUtils.capitalize("your string") == "Your String"

i dont know if there is a function but this would do the job in case there is no exsiting one:

String s = "here are a bunch of words";

final StringBuilder result = new StringBuilder(s.length());
String[] words = s.split("\\s");
for(int i=0,l=words.length;i<l;++i) {
  if(i>0) result.append(" ");      
  result.append(Character.toUpperCase(words[i].charAt(0)))
        .append(words[i].substring(1));

}

Also you can take a look into StringUtils library. It has a bunch of cool stuff.

Related