我想檢查輸入的特定單詞是否在字符串中。我用下面的代碼:搜索指定單詞的字符串
import java.util.*;
import java.io.*;
public class StringTest {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String s1;
s1 = s.next();
String s2 = "this is an accomplishment";
if (s2.contains(s1)) {
System.out.println("you have done it");
} else
System.out.println("try another word");
}
}
如果我輸入單詞「COM」我得到的結果
你都做到了
但「COM」其實只是一部分「成就」一詞。我想要的結果在這種情況下是
嘗試另一個字
因爲s2
不包含完整的單詞「COM」。我也試過indexOf()
,但是這也給出了相同的結果。我應該怎樣進行?