简体   繁体   English

如果我想使用char在Java中检查特殊字符怎么办?

[英]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. 问题是我不知道该怎么做:检查特殊字符或检查ASCII值。 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'语句检查数字ASCII值还是我需要检查每个特殊字符?

You can use regex (Regular Expressions): 您可以使用regex(正则表达式):

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. 如果字符不是字母数字,则将执行if语句中的代码。 (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]" . (空格将被视为特殊字符。)如果您不希望空格被视为特殊字符,请将字符串更改为"[^a-zA-Z0-9\\\\s]"

Further reading: 进一步阅读:

You can use isLetter(char c) and isDigit(char c). 您可以使用isLetter(char c)和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. 编辑:正如评论中指出的那样,使用isLetterOrDigit(char c)可能更可行。

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. EDIT2:正如ostrichofevil指出的那样(我在发布答案时没有想到或知道),该解决方案不会将“非特殊”字符限制为AZ,az和0-9,但将包括任何被认为是Unicode中的字母或数字。 This probably makes ostrichofevil's answer a more practical solution in most cases. 在大多数情况下,这可能使ostrichofevil的答案成为更实际的解决方案。

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;
      }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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