java - 如何检查字符串中的所有字符是否都是字母?

标签 java string character

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

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]+

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

关于java - 如何检查字符串中的所有字符是否都是字母?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20569685/

相关文章:

java - find_java.exe 无法识别 - 在 Android SDK 管理器中...同时安装了 Java 8 更新

java - 调试递归函数

java - 更新记录时如何使用替换方法?

java - 正确显示带线程的 Sprite

regex - 在每行的开头和结尾添加字符串和标签

java - 从文本文件中删除评论

java - 使用正则表达式提取字符串

xslt - 使用 XSLT 1.0 进行 URL 编码

string - Coq 中字符的单引号表示法?

java - AWT 上格式错误的波斯语字符