【问题标题】:Is there a way to count the number of times a word has repeated in a string?有没有办法计算一个单词在字符串中重复的次数?
【发布时间】:2018-11-26 01:45:08
【问题描述】:

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

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

如何获得总章数?(最后一章数)?

例如:chapter 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();

但得到异常:NumberFormatException: For input string: "1 The"

【问题讨论】:

  • 这可以在 Linux 中轻松完成,但您在这里使用 Java 吗?
  • 是的,先生。绝对

标签: java string


【解决方案1】:

因为您的“book”字符串中不仅有空格,而且还有换行符、制表符等。 你应该改用这个正则表达式:

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

【讨论】:

  • 还有特殊字符
【解决方案2】:

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

因此您无需将整个文件加载到内存中,您无需先遍历字符串即可拆分,然后再次遍历以找到匹配项。

【讨论】:

    猜你喜欢
    • 2021-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-09
    • 2014-04-29
    • 2019-07-31
    • 2020-02-28
    • 1970-01-01
    相关资源
    最近更新 更多