简体   繁体   中英

Is there a way to count the number of times a word has repeated in a string?

My string has over 100000 words. Its a book. It contains about x number of chapters:

chapter 1
text text text
chapter 2
text text text 
 and so on

How do I get the total number of chapters?(last chapter number)?

for example: chapter 117

I tried this :

   String[] words = book.split(" ");
        ArrayList<Integer> chapterPositions = new ArrayList<Integer>();
        int count = 0;
        for (String a : words) {
            if (a.equals("Chapter")) {
                chapterPositions.add(count + 1);
            }
            count++;
        }
        num_chapters = Integer.parseInt(words[(chapterPositions.get(chapterPositions.size() - 1))]);
        Toast.makeText(getApplicationContext(), Integer.toString(num_chapters), Toast.LENGTH_LONG).show();

but get exception : NumberFormatException: For input string: "1 The"

Because there is not only space, but there are also new line characters, tab, etc.. in your "book" string. You should use this regular expression instead:

String[] words = book.split("\\s+");

I think a better way would have been reading the file line by line and using a regular expression like Chapter\\\\s+[0-9]+ with the Pattern and Matcher java classes and then count the number of match.

Thus you don't load the entire file in memory, you don't need to first iterate through the string to just split and then iterate again to find a match.

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