且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查字符串中的所有字符是否全部为字母?

更新时间:2023-02-26 12:31:15

我要做的是使用 String#matches 并使用正则表达式 [a-zA-Z] +

What I would do is use String#matches and use the regex [a-zA-Z]+.

String hello = "Hello!";
String hello1 = "Hello";

System.out.println(hello.matches("[a-zA-Z]+"));  // false
System.out.println(hello1.matches("[a-zA-Z]+")); // true






另一种解决方法是 if(Character.isLetter(str.charAt(i))在循环内。

另一个解决方案是这样的

Another solution is something like this

String set = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
String word = "Hello!";

boolean notLetterFound;
for (char c : word.toCharArray()){  // loop through string as character array
    if (!set.contains(c)){         // if a character is not found in the set
        notLetterfound = true;    // make notLetterFound true and break the loop
        break;                       
    }
}

if (notLetterFound){    // notLetterFound is true, do something
    // do something
}






虽然我更喜欢第一个答案,但使用 String#matches