在Java中检查字符串是否仅包含Unicode字母
为了检查Java中的字符串是否仅包含Unicode字母,我们使用isDigit()和charAt()方法以及决策语句。
isLetter(int codePoint)方法确定特定字符(Unicode codePoint)是否为字母。它返回一个布尔值,真或假。
声明 - 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++) {
// checks whether the character is not a letter
// if it is not a letter ,it will return 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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP