到目前爲止,我已經制作了一個程序,可以搜索文本文件中的單個字符串。它確實給出了我搜索的字符串的索引。但是,如何在單個文本文件中搜索多個字符串?在單個文本中進行多次搜索文件
到目前爲止,如果我輸入「愛麗絲」使用掃描儀我的輸出是:
Got a match at line 17
Got a match at line 19
Got a match at line 20
Got a match at line 21
然而,如果可能的話,我怎麼能在我的掃描儀搜索,愛麗絲,約翰,史蒂芬爲我輸入和我的輸出是這樣的:
Got a match for Alice at line 17
Got a match at John at line 19
Got a match at Steven at line 20
Got a match at Steven at line 21
。
public static void main(String[]args) throws IOException{
int nnames;
String[] names;
String stringSearch = null;
Scanner scan = new Scanner(System.in);
//for(int i=1;i<=3;i++){
stringSearch = scan.nextLine();
ArrayList<String> words = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader("File1.txt"));
String line;
while ((line = reader.readLine()) != null) {
words.add(line);
}reader.close();
Collections.sort(words);
System.out.println("ArrayList elements after sorting in ascending order : ");
System.out.println("");
for(int i=0; i<words.size(); i++)
System.out.println(words.get(i));
for(String sLine : words)
{
if (sLine.contains(stringSearch))
{
int index = words.indexOf(sLine);
System.out.println("");
System.out.println("Got a match at line " + index);
}
}
System.out.println(words.size());
}
定義「在單個文件中搜索多個字符串」。 2(或更多)字符串搜索的輸出應該是什麼?你在尋找與這些字符串匹配的索引嗎?請詳細說明。 – amit
@amit我已經更新了這個問題......我希望你能更好地理解它?謝謝 – user1883386