到目前为止,我已经制作了一个程序,可以在文本文件中搜索单个字符串。它确实给出了我搜索的字符串的索引。但是,如何在单个文本文件中搜索多个字符串?
到目前为止,如果我使用扫描仪输入“Alice”,我的输出将是:
Got a match at line 17
Got a match at line 19
Got a match at line 20
Got a match at line 21
但是如果有可能的话,我怎么能在我的扫描仪中搜索,Alice,John,Steven作为我的输入和我的输出如下:
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());
}
答案 0 :(得分:2)
将if
- 块替换为您要查找的所有字符串
for(String sLine : words)
{
for(String searchWord: searchWords)
{
if (sLine.contains(searchWord))
{
int index = words.indexOf(sLine);
System.out.println("");
System.out.println("Got a match of "+searchWord+" at line " + index);
}
}
}
答案 1 :(得分:1)
试试这个
import java.util.Scanner;
import java.util.ArrayList;
import java.util.*;
import java.io.*;
class x{
public static void main(String[]args) throws IOException{
int nnames;
String[] names;
String stringSearch[] = new String[2];
// Scanner scan = new Scanner(System.in);
//for(int i=1;i<=3;i++){
// stringSearch = scan.nextLine();
stringSearch[0]="hello"; //list of words to search
stringSearch[1]="world";
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(int i=0;i<2;i++){
for(String sLine : words)
{
if (sLine.contains(stringSearch[i]))
{
int index = words.indexOf(sLine);
System.out.println("");
System.out.println("Got a match of "+stringSearch[i] +" at line " + index);
}
}}
System.out.println(words.size());
}
}
如果您想从输入中获取所有搜索字符串 然后尝试这个
searchString=item to search seperated by ','
String[] splits = searchString.split(",");