使用ASCII值检查字符串是否仅包含Java中的字母
假设我们在myStr变量中设置了inut字符串。现在循环遍历直到字符串的长度,并检查具有ASCII值的字母-
for (int i = 0; i < myStr.length(); i++) {
char c = myStr.charAt(i);
if (!(c >= 'A' && c <= 'Z') && !(c >= 'a' && c <= 'z')) {
return false;
}
return true;
}以下是检查字符串是否仅包含Java中使用ASCII值的字母的示例;
示例
class Main {
public static boolean checkAlphabet(String myStr) {
for (int i = 0; i < myStr.length(); i++) {
char c = myStr.charAt(i);
if (!(c >= 'A' && c <= 'Z') && !(c >= 'a' && c <= 'z')) {
return false;
}
}
return true;
}
public static void main(String[] args) {
String str1 = "Tom1";
System.out.println("String1 = " + str1);
System.out.println("Is String1 contains only alphabets? = " + checkAlphabet(str1));
String str2 = "Tim";
System.out.println("String2 = " + str2);
System.out.println("Is String2 contains only alphabets? = " + checkAlphabet(str2));
}
}输出结果
String1 = Tom1 Is String1 contains only alphabets? = false String2 = Tim Is String2 contains only alphabets? = true
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短