在 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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
安卓
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP