另一個例子,如果你想尋找一組單詞你裏面輸入
public class TestCheckWord {
static String words = "admin,administrator,babo,sir,melon";
public static void main (String args[]){
System.out.println(checkWord("Hello melon"));
System.out.println(checkWord("Hello sir"));
System.out.println(checkWord("Hello you"));
}
public static boolean checkWord(String input) {
String wordArray[] = words.split(",");
for(int i=0; i<wordArray.length; i++){
if(input.indexOf(wordArray[i])>-1)
return true;
}
return false;
}
}
甚至還有另一種方式來查找單詞只有當你的輸入只包含一個單詞時(在這種情況下,排列順序並不重要)
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class TestCheckWord2 {
public static void main (String args[]){
System.out.println(checkWord("babo"));
System.out.println(checkWord("bobo"));
}
private static String[] WORDS = {"admin", "babo", "melon", "sir", "administrator"};
private static Set<String> mySet = new HashSet<String>(Arrays.asList(WORDS));
public static boolean checkWord(String input) {
return mySet.contains(input);
}
}
對於每個單詞,檢查輸入是否包含/等於? –
我想我沒有正確地得到問題。你想尋找單個單詞,或者你想檢查你的字符串輸入是否包含任何這些單詞? – PbxMan