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

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

问题描述

如何对字符串进行分区以提取其中出现的所有单词/术语,并计算每个单词出现的次数? 例如让: 字符串q = "foo bar foo" 我需要DS {<foo,2>, <bar,1>}.这是我随附的最不繁琐的代码*.过错还是不太冗长的选择?

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天全站免登陆