2016-09-30 27 views
3

因此,我正在用Java編寫一些代碼,並試圖找出是否有方法來編寫一行代碼來檢查字符串中的字符既不是字母也不是數字。我知道:如何檢查一個字符在Java中既不是字母也不是數字?

Character.isDigit()檢查一些

Character.isLetter()檢查了一封信。

但我想知道是否有可能讓java檢查這些代碼中是否都不存在。就像字符串中的「/」或「*」或甚至「_」一樣。

我對Java非常陌生,所以我不確定該去哪裏。

回答

3

您可以將兩個調用組合到一個表達式中,這個表達式的計算結果是一個布爾值。

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

通過德·摩根定律,你也能表達同樣的事情如下:

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

Java provides a method for that - 所有你需要做的就是否定其結果是:

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

無法相信,一直在那裏,因爲1.0 .2我從來沒有注意到它。 (另一方面,我不認爲我曾經用過它。) –

+0

太棒了。這個和@RobertColumbia的代碼都很完美。感謝您的幫助和快速回復。 –

0

代碼檢查字符串中的字符既不是字母也不是 dig它。

從你的問題,我知道你是想傳遞一個String,並檢查該String字符是否只有字母和數字,或者是有別的。

您可以使用正則表達式用於此目的,並檢查您String[^a-zA-Z0-9]

輸出

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

輸入

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; 
    } 
} 
相關問題