在 Java 中檢查一個字串是否只包含Unicode數字


要在 Java 中檢查一個字串是否只包含 Unicode 數字,我們使用 isDigit() 方法和 charAt() 方法以及決策語句。

isDigit(int codePoint) 方法確定特定字元 (Unicode 程式碼點) 是否為數字。它返回一個布林值,為 true 或 false。

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

public static boolean isDigit(int codePoint)

其中引數 codePoint 表示要檢查的字元。

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 not a digit
         if ((Character.isDigit(s.charAt(i)) == false) ) {
            return false; // if it is not a digit then it will return false
         }
      }
      return true;
   }
   public static void main(String [] args) {
      Example e = new Example();
      String s = "1024"; // has only unicode digits so it will return true
      String s1 = "13f4"; // has digits as well as so it will return false
      System.out.println("String "+s+" has only unicode digits : "+e.check(s));
      System.out.println("String "+s1+" has only unicode digits : "+e.check(s1));
   }
}

輸出

String 1024 has only unicode digits : true
String 13f4 has only unicode digits : false

更新日期:2020 年 6 月 26 日

423 次瀏覽

開啟您的職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.