Find all string “the” in .txt file

后端 未结 5 2065
后悔当初
后悔当初 2020-12-31 09:28

Here is my code:

// Import io so we can use file objects
import java.io.*;

public class SearchThe {
    public static void main(String args[]) {
        try         


        
5条回答
  •  误落风尘
    2020-12-31 10:28

    You shouldn't use indexOf because it will find all the possible substring that you have in your string. And because "then" contains the string "the", so it is also a good substring.

    More about indexOf

    indexOf

    public int indexOf(String str, int fromIndex) Returns the index within this string of the first occurrence of the specified substring, starting at the specified index. The integer returned is the smallest value k for which:

    You should separate the lines into many words and loop over each word and compare to "the".

    String [] words = line.split(" ");
    for (String word : words) {
      if (word.equals("the")) {
        System.out.println("Found the word");
      }
    }
    

    The above code snippet will also loop over all possible "the" in the line for you. Using indexOf will always returns you the first occurrence

提交回复
热议问题