用String(Java)计算数字的数量

时间:2014-05-15 19:56:13

标签: java string counting

大家好:)我有一个非常容易的问题我花了2个多小时在这里搜索和java文档。 所以我有一个字符串,每行包含超过5k行,从1-49有6个数字,它们用“;”分隔。我想计算每个数字出现在我很长的字符串中的次数。我发现的大部分主题都是关于计数的。我认为最接近使用常见的lang和函数.countMatches应该使用arrayList吗?我需要一些线索,如果解决方案是长期提示我该怎么做:)

2 个答案:

答案 0 :(得分:1)

直接的解决方案是从您的文件中逐行读取并按;分割,然后您将每个数字作为字符串,最后将它们放入HashMap<String, Integer>,如果密钥存在,只需+ 1的价值。最后,您将获得每个字符串的计数(您的号码)。

我希望我理解你的问题。

答案 1 :(得分:0)

试试这个:

  1. 创建一个变量来保存计数。以下是一个示例:Map<String, Integer> counts = new HashMap<String, Integer>();
  2. 使用String.split()(特别是line.split(“;”)。
  3. 拆分每一行
  4. 每次拆分线路时,您都会收到一组数字。对于每个这些数字,从计数图中检索值。如果为null,则将其添加到计数为1且不为null的地图中,递增计数并将其添加回地图。
  5. 编辑:一些代码。

    Map<String, Integer> counts = new HashMap<String, Integer>();
    String line;
    String[] parts
    
    while (there are more lines)
    {
        line = read the line somehow.
        parts = line.split(";");
        if (parts != null)
        {
            for (String current : parts)
            {
                Integer value = counts.get(current);
                if (value == null) // number not in the counts map yet.
                {
                    counts.put(current, 1);
                }
                else
                {
                    int currentCount = value.intValue() + 1;
                    counts.put(current, currentCount);
                }
            }
        }
    }