Java中檢查字串是否只包含Unicode字母和空格
為了檢查Java中的字串是否只包含Unicode字母,我們使用isDigit()和charAt()方法以及決策語句。
isLetter(int codePoint)方法用於確定特定字元(Unicode codePoint)是否為字母。它返回一個布林值,true或false。
宣告 − java.lang.Character.isLetter()方法宣告如下:
public static boolean isLetter(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) {
int l=0; // counter for number of letters
int sp=0; // counter for number of spaces
if (s == null) // checks if the String is null {
return false;
}
int len = s.length();
for (int i = 0; i < len; i++) {
if ((Character.isLetter(s.charAt(i)) == true)) {
l++;
}
if(s.charAt(i) == ' ') {
sp++;
}
}
if(sp==0 || l==0 ) // even if one of them is zero then returns false
return false;
else
return true;
}
public static void main(String [] args) {
Example e = new Example();
String s = "sid";
String s1 = "y o y";
System.out.println("String "+s+" has only unicode letters and spaces :"+e.check(s));
System.out.println("String "+s1+" has only unicode letters and spaces: "+e.check(s1));
}
}輸出
String s id has only unicode letters and spaces: false String y o y has only unicode letters and spaces: true
廣告
資料結構
網路
關係型資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP