简体   繁体   中英

Search String in an arrayed text file

I took a text file and put it in one array. However, I want to search for a String (word) within the array. In my case I wanted to use the scanner to get input from the user, then search for a string match in the array. How can one achieve such a task?

public static void main(String[]args) throws IOException
{
    //Scanner scan = new Scanner(System.in);
    //String stringSearch = scan.nextLine();
    List<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();
        System.out.println(words);
}

My output:

[CHAPTER I. Down the Rabbit-Hole, Alice was beginning to get very tired of sitting by her sister on the, bank, and of having nothing to do:]
for(int i = 0; i < words.size(); i++){
  if(words.get(i).equals(string)){
     found!!
  }
}

You can use the .contains() function from List. It will use the .equals() method of the parameter on each element

words.contains("your_string")

Just realized you are saving one line per index, and not one word. In this case:

for(String sLine : words) {
    if (sLine.contains("your_string")) {
         System.out.println("Got a match");
         break;
     }
 }

The equals() method suggested by others will only work if you have one word per line. Try iterating over the list and see if one (or more) of the strings contains(word) the word you are looking for?

You can do something with the scanner like this

Scanner sc = new Scanner(new File("File1.txt"));
String targetString = "whatYouWant";
String testString = sc.next();
while(sc.hasNext())
{
    if(testString.equals(targetString))
        hooray!
}

This isn't a full solution but hopefully this will guide you to a working solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM