如何检查String中的所有字符是否都是字母?

时间:2013-12-13 15:09:53

标签: java string character

我能够将句子中的单词分开,但我不知道如何检查单词是否包含字母以外的字符。你不必仅仅发布一些我能读到的材料来帮助我。

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++;
    }            
}   

5 个答案:

答案 0 :(得分:4)

我要做的是使用String#matches并使用正则表达式[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))


另一种解决方案是这样的

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

答案 1 :(得分:1)

更多参考goto-> How to determine if a String has non-alphanumeric characters?
在模式“[^ a-zA-Z ^]”

中进行以下更改

答案 2 :(得分:0)

不确定我是否理解您的问题,但有

Character.isAlpha(C);

您将迭代字符串中的所有字符并检查它们是否是字母(在Character类中还有其他“isXxxxx”方法)。

答案 3 :(得分:0)

您可以循环调用Character.isLetter()一词中的字符,也可以检查它是否与正则表达式匹配,例如[\w]*(只有当其内容都是字符时才会匹配该字词。)

答案 4 :(得分:-1)

你可以使用charector数组来做这个......

char [] a = ss.toCharArray();

不是你可以在perticulor指数上得到这个charector。

用" word" + index +"是" + a [索引];

相关问题