我正在寻找一种方法来对字符串中的一系列单词进行分组和计数。
实施例
String = " 15, 15 , 15 , 2 , 2 , 0 "
我正在寻找的输出是
15(3)
2(2)
0(1)
换句话说,它必须是未排序的,所以我知道序列将是3x15然后2x2和0x1
因此它将具有类似15(3)2(2)0(1)
我试试这段代码
String str = "15|15|15|11|15|15|15|15|15|12|";
String[] splitStr = str.split("\\|");
Map<String, Integer> wordCount = new HashMap<>();
for (String word : splitStr) {
if (wordCount.containsKey(word)) {
// Map already contains the word key. Just increment it's count by 1
wordCount.put(word, wordCount.get(word) + 1);
} else {
// Map doesn't have mapping for word. Add one with count = 1
wordCount.put(word, 1);
}
}
for (Entry<String, Integer> entry : wordCount.entrySet()) {
System.out.println(entry.toString().replaceAll("=","(")+")");
}
但输出变为
15(8) 11(1) 12(1)
我正在寻找像
这样的输出15(3) 11(1) 15(5) 12(1)
答案 0 :(得分:1)
看起来像是作业,不是吗?
如何分割字符串? StringTokenizer
沿着分隔符:空格和逗号;或String.split
,但使用RegEx
如何分组和统计? HashMap
将数字作为键,将其计为值
如何保持密钥的插入顺序:LinkedHashMap
看起来你已经得到了上述内容。您的新要求
“如果一个号码出现不止一次,则应单独计算”
这使得它更复杂一些,你不能用Java内置类做到这一点。
一个小指南:你基本上需要找到序列并计算有多少相同的数字。您将知道前一个和当前(或当前和下一个,取决于您的思维方式)序列边界在哪里是不同的。如果它们是相同的那么你就是中间序列所以只计数。如果它们不同,则需要记下新号码。
在代码中实现以下思路:
15|15|15|11|15|15|15|15|15|12|
^ 15, that's new, we have 1
15|15|15|11|15|15|15|15|15|12|
^ 15 again, we have 2
15|15|15|11|15|15|15|15|15|12|
^ 15 again, we have 3
15|15|15|11|15|15|15|15|15|12|
^ 11, that's new. So 15(3). 11, we have 1
15|15|15|11|15|15|15|15|15|12|
^ 15, that's new. So 11(1). 15, we have 1
15|15|15|11|15|15|15|15|15|12|
^ 15 again, we have 2
15|15|15|11|15|15|15|15|15|12|
^ 15 again, we have 3
15|15|15|11|15|15|15|15|15|12|
^ 15 again, we have 4
15|15|15|11|15|15|15|15|15|12|
^ 15 again, we have 5
15|15|15|11|15|15|15|15|15|12|
^ 12, that's new. So 15(5). 12, we have 1
15|15|15|11|15|15|15|15|15|12|
^ finished so let's not forget the last one 12(1)