检查字符串是否只包含字母 [英] Check if String contains only letters
本文介绍了检查字符串是否只包含字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这个想法是读取一个字符串并验证它不包含任何数字字符.所以像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.
推荐答案
你想要什么?速度还是简单?对于速度,请采用基于循环的方法.为简单起见,请采用基于单行正则表达式的方法.
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]+");
}
这篇关于检查字符串是否只包含字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文