Java中检查字符串是否仅包含Unicode字母或数字


要检查Java中的字符串是否只包含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
         // if it is neither a letter nor a digit then it will return false
         if ((Character.isLetterOrDigit(s.charAt(i)) == false)) {
            return false;
         }
      }
      return true;
   }
   public static void main(String [] args) {
      Example e = new Example();
      String s = "10@4"; // returns false due to special character presence
      String s1 = "13y4"; // returns true
      String s2 = "1000"; // returns true
      String s3= "abcd"; // returns true
      System.out.println("String "+s+" has only unicode letters or digits : "+e.check(s));
      System.out.println("String "+s1+" has only unicode letters or digits : "+e.check(s1));
      System.out.println("String "+s2+" has only unicode letters or digits : "+e.check(s2));
      System.out.println("String "+s3+" has only unicode letters or digits : "+e.check(s3));
   }
}

输出

String 10@4 has only unicode letters or digits : false
String 13y4 has only unicode letters or digits : true
String 1000 has only unicode letters or digits : true
String abcd has only unicode letters or digits : true

更新于:2020年6月26日

6K+ 次浏览

开启你的职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.