java - 字符串在同一行出现的次数

标签 java hashmap bufferedreader indexof

我有代码可以计算文本文件中一周中出现的天数。截至目前,如果它是该行上唯一的字符串,它只会计算一周中的某一天。例如,如果我有一行显示(星期一 abcd),则不会将星期一计入计数中。我尝试使用 indexOf 并通过拆分、修剪和添加回 HashMap 来解决此问题,但我不知道该怎么做。

这是一些代码,在此之前我声明关键字,打开文本文件并将每个关键字放入 map 中,其值为零

public class DayCounter
{

public static void main(String args[]) throws IOException 
{

    String[] theKeywords = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};

    // put each keyword in the map with value 0 
    Map<String, Integer> DayCount = new HashMap<String, Integer>();
    for (String str : theKeywords)
    {
        DayCount.put(str, 0);
    }

    try (BufferedReader br = new BufferedReader(new FileReader("C:\\Eclipse\\test.txt")))
    {

String sCurrentLine;

// read lines until reaching the end of the file
 while ((sCurrentLine = br.readLine()) != null) 
 {


   if (sCurrentLine.length() != 0) 
    {

    // extract the words from the current line in the file
     if (DayCount.containsKey(sCurrentLine))
     {
      DayCount.put(sCurrentLine, DayCount.get(sCurrentLine) + 1);
     }
    }
  }

这是输出部分

 for(String day : theKeywords)
 {
  System.out.println(day + " = " + DayCount.get(day));

 }

最佳答案

您需要在字符串中搜索一周中的实际天数。现在您要问“DayCount 是否包含名为[整行] 的键”,您想要的是检查每一行中一周中每一天的所有出现情况。一种快速但肮脏的方法是分割该单词周围的字符串(例如“Monday”)并计算结果列表的长度:

while ((sCurrentLine = br.readLine()) != null) {
    // For every line in the reader...

    for (String dayOfWeek : (Set<String>) DayCount.keySet()) {
        // For each day of the week (the keys in the DayCount map), count how
        // many times that key shows up in the line.
        int occurrences = sCurrentLine.split(dayOfWeek, -1).length - 1;

        // Now increase the appropriate counter by the number of occurrences (0+)
        DayCount.put(dayOfWeek, (Integer) DayCount.get(dayOfWeek) + occurrences);
    }
}

由于您在迭代集合时遇到问题(这是一个谜,但超出了您原来问题的范围),您也可以这样写(正如我在评论中提到的 - 请注意内循环):

while ((sCurrentLine = br.readLine()) != null) {
    // For every line in the reader...

    //NOTE: I strongly advise renaming theKeywords to something more descriptive!
    for (String dayOfWeek : theKeywords) {
        // For each day of the week, count how many times that key shows up.
        int occurrences = sCurrentLine.split(dayOfWeek, -1).length - 1;

        // Now increase the appropriate counter by the number of occurrences (0+)
        DayCount.put(dayOfWeek, (Integer) DayCount.get(dayOfWeek) + occurrences);
    }
}

这一切都非常简单;唯一奇怪的是:

int occurrences = sCurrentLine.split(dayOfWeek, -1).length - 1;

此代码在当前行调用 split 方法。它在一周中的某一天进行分割,并使用一个看起来很尴尬的 -1 作为“maxSplits”。这个负值告诉 split 方法在结果的行末尾包含空字符串。否则,行 "a b c Monday " 将按预期返回长度为 2 的数组 (["a b c ", ""]),而行 "a b c Monday”(末尾没有空格)将返回一个长度为 1 的数组,因为最后一项为空。

一旦我们围绕一周中的某一天正确分割了数组,我们就会计算其中的项目数并减一以获得实际出现的次数。这始终是合法的,因为我们的数组的最小大小是 1(在没有发生拆分的情况下,因此原始 String 是返回数组中的唯一元素)。

关于java - 字符串在同一行出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15256875/

相关文章:

java - 为什么HashMap取容量为容量<<= 1;

Java - 读取文件并加载到 HashMap - 如何减少时间?

java - 一种将共享资源分配给多个节点中的一个节点的分布式算法

java - Spark - 方案 : https, 的无文件系统无法从 Amazon S3 加载文件

java - 如何保留 Map.of 工厂中的插入顺序?

java - 从 HashMap 中获取特定数据

java - 读取文件时需要相应地跳过行号(了解更多)

java - 读取和写入同一文件 - 输出格式更改

java - 如何从 Cloud firestore 获取数据并使用回收器 View 显示

java - 使用 Java 反射检索继承的属性名称/值