在字符串上查找重复的单词并计算重复次数
我需要在字符串上找到重复的单词,然后计算它们重复了多少次.所以基本上,如果输入字符串是这样的:
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.