Flu Hatin' Rapper
Flu Hatin' Rapper

Reputation: 21

Trying to convert characters to upper case using ASCII values (can't use toUpperCase())

Every time I try to convert a character using ASCII values, I get '?' as the result. I assume it is a casting issue, but I have been trying to fix it for quite some time now with no success.

Here is a snippet of my code:

    String x = arr[j];
    char firstChar = x.charAt(0);
    firstChar += (char)32;

No matter what character I operate on, I get '?' as the result.

Thanks for your time and help.

Upvotes: 0

Views: 1396

Answers (3)

kyw5lien
kyw5lien

Reputation: 1

UpperCase to LowerCase:

public static char toUpperCase(char c){
    int charASCIICode = (int) c;
    if (charASCIICode >= 97 && charASCIICode <= 122)
        return (char) (charASCIICode - 32);

    return c;
}

Upvotes: 0

Kevin Krumwiede
Kevin Krumwiede

Reputation: 10308

If you wanted to convert lower case to upper case, you would subtract 32, not add it. And you should first test that the character is in the range of lower case letters, which is 97-122, inclusive.

Upvotes: 3

JB Nizet
JB Nizet

Reputation: 691893

Replace

firstChar += (char)32;

by

firstChar -= 32;

Uppercase letters come before lowercase letters.

Upvotes: 3

Related Questions