Java Counting # of occurrences of a word in a string

前端 未结 8 1851
再見小時候
再見小時候 2020-12-03 19:20

I have a large text file I am reading from and I need to find out how many times some words come up. For example, the word the. I\'m doing this line by line e

8条回答
  •  余生分开走
    2020-12-03 19:55

    Splitting the Strings sounds like a lot of overhead just to find out the number of occurrences in a file. You could use String.indexOf(String, int) to recursively go through the whole line/file, like this:

    int occurrences = 0;
    int index = 0;
    while (index < s.length() && (index = s.indexOf("the", index)) >= 0) {
        occurrences++;
        index + 3; //length of 'the'
    }
    

提交回复
热议问题