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

How to check if all characters in a String are all letters?

我可以将句子中的单词分开,但是我不知道如何检查单词是否包含字母以外的其他字符。 您不必只发布一些我可以阅读以帮助我的材料的答案。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public static void main(String args [])
{
    String sentance;
    String word;
    int index = 1;

    System.out.println("Enter sentance please");
    sentance = EasyIn.getString();

    String[] words = sentance.split("");    

    for ( String ss : words )
    {
        System.out.println("Word" + index +" is" + ss);
        index++;
    }            
}

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

1
2
3
4
5
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))

另一个解决方案是这样的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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的第一个答案


有关更多参考,请转到->如何确定字符串是否包含非字母数字字符?
在模式" [^ a-zA-Z ^]"中进行以下更改


您可以循环调用单词Character.isLetter()中的字符,或者检查它是否与正则表达式匹配,例如[\\w]*(仅当单词的内容全部为字符时,此单词才匹配)。


不知道我是否理解您的问题,但是有

Character.isAlpha(c);

您将遍历字符串中的所有字符,并检查它们是否为字母(Character类中还有其他" isXxxxx"方法)。


您可以使用charector数组来完成此操作。

char [] a = ss.toCharArray();

不是你可以得到小孔指数的特征。

" word" + index +"是" + a [index];