检查字符串是否在Java中仅包含unicode字母,数字或空格
要检查给定的String是否仅包含unicode字母,数字或空格,我们将isLetterOrDigit()andcharAt()方法与决策语句一起使用。
isLetterOrDigit(charch)方法确定特定字符(Unicodech)是字母还是数字。它返回一个布尔值,为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++) {
//检查字符是否既不是字母也不是数字,甚至不是空格
//如果它既不是字母也不是数字,甚至不是空格,那么它将返回false-
if ((Character.isLetterOrDigit(s.charAt(i)) == false) && s.charAt(i)!=' ') {
return false;
}
}
return true;
}
public static void main(String [] args) {
Example e = new Example();
String s = "@ # @"; // returns false due to special character presence
String s1 = "134s"; // returns true
String s2 = "1 0d"; // returns true
String s3 = "1 x"; // returns true
System.out.println("String "+s+" has only unicode letters,digits or space : "+e.check(s));
System.out.println("String "+s1+" has only unicode letters,digits or space: "+e.check(s1));
System.out.println("String "+s2+" has only unicode letters,digits or space: "+e.check(s2));
System.out.println("String "+s3+" has only unicode letters,digits or space : "+e.check(s3));
}
}输出结果
String @ # @ has only unicode letters,digits or space : false String 134s has only unicode letters,digits or space: true String 1 0d has only unicode letters,digits or space: true String 1 x has only unicode letters,digits or space : true