tags:

views:

165

answers:

2

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:

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
hey thx a lot!!
+3  A: 

Apache Commons StringUtils.capitalize()

aberrant80
+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