Java 中檢查字串是否只包含 Unicode 字母、數字或空格


要檢查給定的字串是否只包含 Unicode 字母、數字或空格,我們使用 isLetterOrDigit() 和 charAt() 方法以及決策語句。

isLetterOrDigit(char ch) 方法確定特定字元(Unicode ch)是字母還是數字。它返回一個布林值,要麼為 true 要麼為 false。

宣告 - java.lang.Character.isLetter() 方法的宣告如下:

public static boolean isLetter(char ch)

charAt() 方法返回給定索引處的字元值。它屬於 Java 中的 String 類。索引必須在 0 到 length()-1 之間。

宣告 - java.lang.String.charAt() 方法的宣告如下:

public char charAt(int index)

讓我們來看一個 Java 程式,它檢查字串是否只包含 Unicode 字母、數字或空格。

示例

 線上演示

public class Example {
   boolean check(String s) {
      if (s == null) // checks if the String is null {
         return false;
      }
      int len = s.length();
      for (int i = 0; i < len; i++) {
         // checks whether the character is neither a letter nor a digit and not even a space
         // if it is neither a letter nor a digit and not even a space then it will return false
         if ((Character.isLetterOrDigit(s.charAt(i)) == false) && s.charAt(i)!=' ') {
            return false;
         }
      }
      return true;
   }
   public static void main(String [] args) {
      Example e = new Example();
      String s = "@ # @"; // returns false due to special character presence
      String s1 = "134s"; // returns true
      String s2 = "1 0d"; // returns true
      String s3 = "1 x"; // returns true
      System.out.println("String "+s+" has only unicode letters,digits or space : "+e.check(s));
      System.out.println("String "+s1+" has only unicode letters,digits or space: "+e.check(s1));
      System.out.println("String "+s2+" has only unicode letters,digits or space: "+e.check(s2));
      System.out.println("String "+s3+" has only unicode letters,digits or space : "+e.check(s3));
   }
}

輸出

String @ # @ has only unicode letters,digits or space : false
String 134s has only unicode letters,digits or space: true
String 1 0d has only unicode letters,digits or space: true
String 1 x has only unicode letters,digits or space : true

更新於: 2020-06-25

796 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.