Converting a lowercase char to uppercase without using an if statement

2.1k Views Asked by At

How I can convert a lowercase char to uppercase without using an if statement?. I.e. don't use code like this:

if(c > 'a' && c < 'z')
{
    c = c-32;
}
4

There are 4 best solutions below

0
Martijn Courteaux On BEST ANSWER

If you are sure that your characters are ASCII alphabetic, then you can unset the bit that makes it lowercase, since the difference between the lowercase and uppercase latin chars is only one bit in the ASCII table.

You can simply do:

char upper = c & 0x5F;
0
Warlord On

You can use this:

char uppercase = Character.toUpperCase(c);
1
The Guy with The Hat On

Use Character.toUpperCase(char):

Converts the character argument to uppercase using case mapping information from the UnicodeData file.

For example, Character.toUpperCase('a') returns 'A'.

So the full code you probably want is:

c = Character.toUpperCase(c);
2
tcollart On

You can use the ternary operator. For your case, try something like this:

c = (c >= 'a' && c <= 'z') ? c = c - 32 : c;