简体   繁体   中英

What do I do if I want to check for a special character in Java using char?

I want to create a program for checking whether any inputted character is a special character or not. The problem is that I hava no idea what to do: either check for special characters or check for the ASCII value. Can anyone tell me if I can just check for the numerical ASCII value using 'if' statement or if I need to check each special character?

You can use regex (Regular Expressions):

if (String.valueOf(character).matches("[^a-zA-Z0-9]")) {
    //Your code
}

The code in the if statement will execute if the character is not alphanumeric. (whitespace will count as a special character.) If you don't want white space to count as a special character, change the string to "[^a-zA-Z0-9\\\\s]" .

Further reading:

You can use isLetter(char c) and isDigit(char c). You could do it like this:

char c;
//assign c in some way
if(!Character.isLetter(c) && !Character.isDigit(c)) {
    //do something in case of special character
} else {
    //do something for non-special character
}

EDIT: As pointed out in the comments it may be more viable to use isLetterOrDigit(char c) instead.

EDIT2: As ostrichofevil pointed out (which I did not think or know of when i posted the answer) this solution won't restrict "non-special" characters to AZ, az and 0-9, but will include anything that is considered a letter or number in Unicode. This probably makes ostrichofevil's answer a more practical solution in most cases.

you can achieve it in this way :

char[] specialCh = {'!','@',']','#','$','%','^','&','*'}; // you can specify all special characters in this array

boolean hasSpecialChar = false;

char current;

for (Character c : specialCh) {
      if (current == c){
          hasSpecialChar = true;
      }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM