any built in methods available to convert a string into titlecase format as such??
+2
A:
there are no capitalize() or titleCase() methods in String class. You have two choices:
- using commons lang string utils.
- write (yet another) static helper method toTitleCase()
Sample implementation
public static String toTitleCase(String input) {
StringBuilder titleCase = new StringBuilder();
boolean nextTitleCase = true;
for (char c : input.toCharArray()) {
if (Character.isSpaceChar(c)) {
nextTitleCase = true;
} else if (nextTitleCase) {
c = Character.toTitleCase(c);
nextTitleCase = false;
}
titleCase.append(c);
}
return titleCase.toString();
}
Testcase
System.out.println(toTitleCase("string"));
System.out.println(toTitleCase("another string"));
System.out.println(toTitleCase("YET ANOTHER STRING"));
outputs:
String Another String YET ANOTHER STRING
dfa
2009-07-06 09:09:18
hey thx a lot!!
2009-07-06 10:04:31
+1 for suggesting library use. Common sense reigns for once. However, I'd suggest the use of WordUtils instead of StringUtils, it's got a more flexible set of options.
skaffman
2009-07-06 09:17:31