检查字符串是否在Java中仅包含unicode字母
为了检查Java中的String是否只有Unicode字母,我们将isDigit()andcharAt()方法与决策语句一起使用。
isLetter(intcodePoint)方法确定特定字符(UnicodecodePoint)是否为字母。它返回一个布尔值,为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) {
if (s == null) // checks if the String is null {
return false;
}
int len = s.length();
for (int i = 0; i < len; i++) {
//检查字符是否不是字母
//如果不是字母,则返回false-
if ((Character.isLetter(s.charAt(i)) == false)) {
return false;
}
}
return true;
}
public static void main(String [] args) {
Example e = new Example();
String s = "@asd"; // returns false due to special character presence
String s1 = "134s"; // returns false due to presence of digits
String s2 = "abcd"; // returns true
String s3= "g c1"; // returns false due to space and digits
System.out.println("String "+s+" has only unicode letters : "+e.check(s));
System.out.println("String "+s1+" has only unicode letters : "+e.check(s1));
System.out.println("String "+s2+" has only unicode letters : "+e.check(s2));
System.out.println("String "+s3+" has only unicode letters : "+e.check(s3));
}
}输出结果
String @asd has only unicode letters : false String 134s has only unicode letters : false String abcd has only unicode letters : true String g c1 has only unicode letters : false