Converting a lowercase char in a char array to an

2019-07-17 03:25发布

问题:

Hello I am trying to write a little segment of code that checks if each char in a char array is lower case or uppercase. Right now it uses the char's ASCII number to check. After it checks it should convert the char to upper case if it is not already so:

for (int counter = 0; counter < charmessage.length; counter++) {
    if (91 - charmessage[counter] <= 0 && 160 - charmessage[counter] != 0) {
    charmessage[counter] = charmessage[counter].toUpperCase();
    } 
}

charmessage is already initialized previously in the program. The 160 part is to make sure it doesn't convert a space to uppercase. How do I get the .toUpperCase method to work?

回答1:

I would do it this way. First check if the character is a letter and if it is lowercase. After this just use the Character.toUpperCase(char ch)

if(Character.isLetter(charmessage[counter]) && Character.isLowerCase(charmessage[counter])){
    charmessage[counter] = Character.toUpperCase(charmessage[counter]);
}


回答2:

You can use the Character#toUpperCase for that. Example:

char a = 'a';
char upperCase = Character.toUpperCase(a);

It has some limitations, though. It's very important you know that the world is aware of many more characters that can fit within the 16-bit range.