Java 有没有办法计算一个单词在字符串中重复的次数?

Java 有没有办法计算一个单词在字符串中重复的次数?,java,string,Java,String,我的字符串有100000多个单词。这是一本书。它包含大约x个章节: chapter 1 text text text chapter 2 text text text and so on 如何获得总章节数?(最后一章数) 例如:第117章 我试过这个: String[] words = book.split(" "); ArrayList<Integer> chapterPositions = new ArrayList<Integer>();

我的字符串有100000多个单词。这是一本书。它包含大约x个章节:

chapter 1
text text text
chapter 2
text text text 
 and so on
如何获得总章节数?(最后一章数)

例如:
第117章

我试过这个:

   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();
String[]words=book.split(“”);
ArrayList chapterPositions=新的ArrayList();
整数计数=0;
for(字符串a:单词){
如果(a.等于(“章节”)){
章节位置。添加(计数+1);
}
计数++;
}
num_chapters=Integer.parseInt(words[(chapterPositions.get(chapterPositions.size()-1)));
Toast.makeText(getApplicationContext(),Integer.toString(num_chapters),Toast.LENGTH_LONG.show();

但是获取异常:NumberFormatException:对于输入字符串:“1”

,因为不仅有空格,还有新行字符、制表符等。。在你的“书”字串里。 应改用此正则表达式:

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

我认为更好的方法是逐行读取文件,并使用正则表达式,如
Chapter\\s+[0-9]+
Matcher
java类,然后计算匹配数


因此,您不需要将整个文件加载到内存中,您不需要先迭代字符串以进行拆分,然后再次迭代以找到匹配项。

在Linux中,这可以很容易地完成,但您在这里使用Java吗?是的,先生。当然也有一些特殊的角色