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
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP