使用 ASCII 值检查字符串是否仅包含 Java 中的字母
假设我们已经将输入字符串设置在 myStr 变量中。现在循环到字符串的长度并使用 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; }
以下是使用 ASCII 值检查字符串是否仅包含 Java 中字母的示例;
实例
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
广告