我使用了很多indexOf()
和的substring()
方法java.lang.String
,这可能会降低代码的性能,但下面的代码可以作为迈向这种方法的第一步。
public class MultiWordCompare {
private static boolean containsWord(String word, String search) {
if(word.indexOf(search) >= 0) { // Try if the word first exists at all
try {
String w = word.substring(word.indexOf(search), word.indexOf(search)+search.length()+1); //+1 to capture possible space
if(w.lastIndexOf(" ") == w.length()-1) { //if the last char is space, then we captured the whole word
w = w.substring(0, w.length()-1); //remove space
return w.equals(search); //do string compare
}
}
catch(Exception e) {
//catching IndexOutofBoundException
}
}
return false;
}
public static void main(String [] args) {
System.out.println(containsWord("New York is great!", "New York"));
System.out.println(containsWord("Many many happy Returns for the day", "happy Returns"));
System.out.println(containsWord("New Authority", "New Author"));
System.out.println(containsWord("New York City is great!", "N Y C"));
}
}
这是输出
true
true
false
false