简体   繁体   中英

How do I check if a character is neither a letter nor a digit in Java?

So I'm writing some code in Java and I'm trying to find out if there is a way to write a line of code that checks if a character in a string is neither a letter nor a digit. I know that:

Character.isDigit() checks for a number

and

Character.isLetter() checks for a letter.

But I want to know if it is possible for java to check if neither of these are present in a single line of code. Like if the character is "/" or "*" or even "_" in the string.

I'm very new to Java so I'm not sure where to go at this point.

Java provides a method for that - all you need to do is to negate its result:

if (!Character.isLetterOrDigit(ch)) {
    ...
}

You can combine both calls in a single expression that evaluates to a boolean.

if (!(Character.isDigit()) && !(Character.isLetter()) ) {
    //The character is neither a digit nor a letter.
    // Do whatever
}

By De Morgan's law, you can also express the same thing as follows:

if (!((Character.isDigit()) || (Character.isLetter()) )) {
   //The statement "The character is a digit or a letter" is false.    
   // Do whatever
}

code that checks if a character in a string is neither a letter nor a digit.

From your question, I understand that you want to pass a String and check whether characters in that String are only letters and digits, or is there anything else.

You can use Regular Expressions for this purpose and check your String against [^a-zA-Z0-9]

Output

loremipsum -> false
loremipsum999 -> false
loremipsum_ -> true
loremipsum/ -> true

Input

import java.util.regex.*;

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("loremipsum -> " + checkForCharAndDigits("loremipsum"));
        System.out.println("loremipsum999 -> " + checkForCharAndDigits("loremipsum999"));
        System.out.println("loremipsum_ -> " + checkForCharAndDigits("loremipsum_"));
        System.out.println("loremipsum/ -> " + checkForCharAndDigits("loremipsum/"));
    }

    public static boolean checkForCharAndDigits(String str) {
        Matcher m = Pattern.compile("[^a-zA-Z0-9]").matcher(str);
        if (m.find()) return true;
        else          return false;
    }
}

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