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