在Java中檢查字串是否僅包含Unicode字母


為了檢查Java中的字串是否僅包含Unicode字母,我們使用isDigit()和charAt()方法以及決策語句。

isLetter(int codePoint)方法確定特定字元(Unicode codePoint)是否為字母。它返回一個布林值,真或假。

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

public static boolean isLetter(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 letter
         // if it is not a letter ,it will return false
         if ((Character.isLetter(s.charAt(i)) == false)) {
            return false;
         }
      }
      return true;
   }
   public static void main(String [] args) {
      Example e = new Example();
      String s = "@asd"; // returns false due to special character presence
      String s1 = "134s"; // returns false due to presence of digits
      String s2 = "abcd"; // returns true
      String s3= "g c1"; // returns false due to space and digits
      System.out.println("String "+s+" has only unicode letters : "+e.check(s));
      System.out.println("String "+s1+" has only unicode letters : "+e.check(s1));
      System.out.println("String "+s2+" has only unicode letters : "+e.check(s2));
      System.out.println("String "+s3+" has only unicode letters : "+e.check(s3));
   }
}

輸出

String @asd has only unicode letters : false
String 134s has only unicode letters : false
String abcd has only unicode letters : true
String g c1 has only unicode letters : false

更新於: 2020年6月26日

11K+ 瀏覽量

啟動你的職業生涯

透過完成課程獲得認證

開始學習
廣告