检查 Java 中的字符串是否仅包含 unicode 数字或空格


为了检查 Java 中的字符串是否仅包含 unicode 数字或空格,我们使用 isDigit() 方法和带有决策语句的 charAt() 方法。

isDigit(int codePoint) 方法确定特定字符(Unicode codePoint)是否为数字。它返回一个布尔值,为 true 或 false。

声明 - java.lang.Character.isDigit() 方法声明如下 −

public static boolean isDigit(int 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 and not a space
            if ((Character.isDigit(s.charAt(i)) == false) && (s.charAt(i) != ' ')) {
            return false; // if it is not any of them then it returns false
         }
      }
      return true;
   }
   public static void main(String [] args) {
      Example e = new Example();
      String s = "0090"; // has only digits so it will return true
      String s1 = "y o y"; // has spaces but also has letters so it will return false
      System.out.println("String "+s+" has only unicode digits or spaces: "+e.check(s));
      System.out.println("String "+s1+" has only unicode digits or spaces: "+e.check(s1));
   }
}

输出

String 0090 has only unicode digits or spaces: true
String y o y has only unicode digits or spaces: false

更新于: 2020 年 6 月 26 日

四千多次浏览

开启你的 职业生涯

完成课程,获得认证

开始
广告
© . All rights reserved.