Search code examples
javaandroidstringcapitalize

How to capitalize each letter after a special letter in android?


First of all, please don't mark it as duplicate.

I have a very specific problem. I have to capitalize each word's first letter. Problem is that I can't find-out when a word start.

For example, I have given String:

0nd0-cathay bank (federal saving)

And output should be as following:

0Nd0-Cathay Bank (Federal Saving).

Currently I'm having following method for title case:

public static String toTitleCase(String str) 
{
    if (str == null) 
        return "";

    boolean space = true;
    StringBuilder builder = new StringBuilder(str);
    final int len = builder.length();

    for (int i=0; i < len; ++i) 
    {
        char c = builder.charAt(i);

        if (space) 
        {
            if (!Character.isWhitespace(c)) 
            {
                // Convert to title case and switch out of whitespace mode.
                builder.setCharAt(i, Character.toTitleCase(c));
                space = false;
            }
        } 
        else if (Character.isWhitespace(c)) 
        {
            space = true;
        } 
        else 
        {
            builder.setCharAt(i, Character.toLowerCase(c));
        }
    }

    return builder.toString();
}

Thanks all.


Solution

  • You can use the following solution with regex (not the prettiest though).

    String input = "0nd0-cathay bank (federal saving)";
    // case-sensitive Pattern:
    //                              | group 1: first letter
    //                              |      | group 2: any other character if applicable
    //                              |      |    | word boundary
    Pattern p = Pattern.compile("([a-z])(.*?)\\b");
    // Pattern for all capital letters 
    // Pattern p = Pattern.compile("([A-Z])(.*?)\\b");
    // initializing StringBuffer for appending
    StringBuffer sb = new StringBuffer();
    Matcher m = p.matcher(input);
    // iterating over matches
    while (m.find()) {
       // appending replacement:
       //                      | 1st letter capitalized
       //                      |                        | concatenated with...
       //                      |                        |     | any other character
       //                      |                        |     | within word boundaries
       m.appendReplacement(sb, m.group(1).toUpperCase().concat(m.group(2)));
       // Replacement for all capital letters
       // m.appendReplacement(sb, m.group(1).concat(m.group(2).toLowerCase()));
    }
    // appending tail if any
    m.appendTail(sb);
    System.out.println(sb.toString());
    

    Output

    0Nd0-Cathay Bank (Federal Saving)
    

    Notes

    • This will capitalize the first alphabetic character in all words, even if words do not start with an alphabetic character.
    • For instance, 0nd0 becomes 0Nd0.
    • If you don't want this edge case after all, prepend a word boundary (\\b) to the Pattern.