检查String是否仅包含字母 [英] Check if String contains only letters
本文介绍了检查String是否仅包含字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我们的想法是读取一个String并验证它是否包含任何数字字符。所以像smith23这样的东西是不可接受的。
The idea is to have a String read and to verify that it does not contain any numeric characters. So something like "smith23" would not be acceptable.
推荐答案
你想要什么?速度还是简单?为了速度,请采用基于循环的方法。为简单起见,请采用单行基于RegEx的方法。
What do you want? Speed or simplicity? For speed, go for a loop based approach. For simplicity, go for a one liner RegEx based approach.
速度
public boolean isAlpha(String name) {
char[] chars = name.toCharArray();
for (char c : chars) {
if(!Character.isLetter(c)) {
return false;
}
}
return true;
}
简洁
public boolean isAlpha(String name) {
return name.matches("[a-zA-Z]+");
}
这篇关于检查String是否仅包含字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文