在字符串上查找重复的单词并计算重复次数 [英] Finding repeated words on a string and counting the repetitions

查看:117
本文介绍了在字符串上查找重复的单词并计算重复次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在字符串上找到重复的单词,然后计算它们重复了多少次.所以基本上,如果输入字符串是这样的:

I need to find repeated words on a string, and then count how many times they were repeated. So basically, if the input string is this:

String s = "House, House, House, Dog, Dog, Dog, Dog";

我需要创建一个没有重复的新字符串列表,并将每个单词的重复次数保存在其他地方,例如:

I need to create a new string list without repetitions and save somewhere else the amount of repetitions for each word, like such:

新字符串:房子,狗"

新的整数数组:[3, 4]

New Int Array: [3, 4]

有没有办法用 Java 轻松地做到这一点?我已经设法使用 s.split() 分隔字符串,但是如何计算重复并在新字符串上消除它们?谢谢!

Is there a way to do this easily with Java? I've managed to separate the string using s.split() but then how do I count repetitions and eliminate them on the new string? Thanks!

推荐答案

您已经完成了艰苦的工作.现在您可以使用 Map 来计算出现次数:

You've got the hard work done. Now you can just use a Map to count the occurrences:

Map<String, Integer> occurrences = new HashMap<String, Integer>();

for ( String word : splitWords ) {
   Integer oldCount = occurrences.get(word);
   if ( oldCount == null ) {
      oldCount = 0;
   }
   occurrences.put(word, oldCount + 1);
}

使用 map.get(word) 会告诉你一个词出现了多少次.您可以通过遍历 map.keySet() 来构造一个新列表:

Using map.get(word) will tell you many times a word occurred. You can construct a new list by iterating through map.keySet():

for ( String word : occurrences.keySet() ) {
  //do something with word
}

请注意,您从 keySet 中得到的内容的顺序是任意的.如果您需要在单词首次出现在输入字符串中时对其进行排序,则应改用 LinkedHashMap.

Note that the order of what you get out of keySet is arbitrary. If you need the words to be sorted by when they first appear in your input String, you should use a LinkedHashMap instead.

这篇关于在字符串上查找重复的单词并计算重复次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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