如何计算字符串数组中的重复项? [英] How to count duplicates in an array of strings?

查看:24
本文介绍了如何计算字符串数组中的重复项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何对字符串进行分区以提取其中出现的所有单词/术语并计算每个出现的次数?例如让:String q = "foo bar foo"我想要一个 DS {, }.这是我编写的代码中最不冗长的代码*.错误或不那么冗长的替代方案?

How do I partition a String to extract all the words/terms that occur in it and count how many times each occurs? For example let: String q = "foo bar foo" I want a DS {<foo,2>, <bar,1>}. This is the least verbose code I code come with*. Faults or less verbose alternatives?

String[] split = q.toString().split("\\s");
        Map<String, Integer> terms = new HashMap<String, Integer>();

        for (String term : split) {
            if(terms.containsKey(term)){
                terms.put(term, terms.get(term)+1);
            }
        }

(还没编译)

推荐答案

修改代码:

String[] split = q.toString().split("\\s");
Map<String, Integer> terms = new HashMap<String, Integer>();

for (String term : split) {
    int score = 0;
    if(terms.containsKey(term)){
        score = terms.get(term);
    }

    terms.put(term, score +1);
}

PS:未经测试.

这篇关于如何计算字符串数组中的重复项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆