检查字符串在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中的程序,以检查String是否仅包含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++) {
         //检查字符是否既不是字母也不是数字
         //如果它既不是字母也不是数字,则将返回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 : falseString 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
以上是 检查字符串在Java中是否仅包含unicode字母或数字 的全部内容, 来源链接: utcz.com/z/316146.html








