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?
-
if only there was an expression you could use on a regular basis to do that... hmmm its a shame really – SaggingRufus Mar 23 '17 at 18:12
-
3special character as in... not [a-zA-Z0-9] ? – Wietlol Mar 23 '17 at 18:14
-
2Could you clarify your question? Maybe give us some example and clarify what you mean by *special*. – Pshemo Mar 23 '17 at 18:15
-
1Possible duplicate of [JAVA: check a string if there is a special character in it](http://stackoverflow.com/questions/1795402/java-check-a-string-if-there-is-a-special-character-in-it) – Benjamin Diaz Mar 23 '17 at 18:16
3 Answers
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:

- 749
- 7
- 19
-
2Maybe add a link to http://www.regex101.com ? its perfectly if you want to build a regular expression – Wietlol Mar 23 '17 at 18:30
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 A-Z, a-z 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.

- 21
- 5
-
Note that `Character.isLetter` will return true for any Unicode character classified as a letter, not just the letters *a-z* and *A-Z*. The same goes for `isDigit`; there are other characters than *0-9* which are classified as digits. – ostrichofevil Mar 23 '17 at 18:27
-
use `!Character.isLetterOrDigit(c);` rather than using && operation. However code will return true for `$ _ ` and so on. – Sanjay Madnani Mar 23 '17 at 18:39
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;
}
}

- 2,200
- 1
- 15
- 37