我可以将句子中的单词分开,但我不知道如何检查单词是否包含字母以外的字符。您不必发布答案,只需发布一些我可以阅读的 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/