code578841441 code578841441 - 7 months ago 9
Java Question

How can I uppercase and lowercase a Char

GWT is not allowing me to use

Character.toUpperCase(char)
and
Character.toLowerCase(char)
. How can I rewrite the method bellow to not use the
Character
class or any external library

public static String toDisplayCase(String s) {

final String ACTIONABLE_DELIMITERS = " '-/"; // these cause the character following
// to be capitalized

StringBuilder sb = new StringBuilder();
boolean capNext = true;

for (char c : s.toCharArray()) {
c = (capNext)
? Character.toUpperCase(c)
: Character.toLowerCase(c);
sb.append(c);
capNext = (ACTIONABLE_DELIMITERS.indexOf((int) c) >= 0); // explicit cast not needed
}
return sb.toString();
}

Answer

If somehow, you are not allowed to use Character class (though that sounds quite crazy), you may add or subtract ASCII values.

eg:

for (char c : s.toCharArray()) {
    c = (capNext)
            ?  ( (c>='a'&&c<='z') ? c+32 : c) //to Upper Case
            :  ( (c>='A'&&c<='Z') ? c-32 : c) //to Lower Case
    sb.append(c);
    capNext = (ACTIONABLE_DELIMITERS.indexOf((int) c) >= 0); // explicit cast not needed
}