我能够将句子中的单词分开,但我不知道如何检查单词是否包含字母以外的字符。您不必发布答案,只需我可以阅读的一些材料来帮助我。
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++;
}
}
Run Code Online (Sandbox Code Playgroud)
我会做的是使用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
Run Code Online (Sandbox Code Playgroud)
另一个解决方案是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
}
Run Code Online (Sandbox Code Playgroud)
不过,我更喜欢第一个答案,使用 String#matches