檢查 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP