java Map集合计算一个字符串中每个字符出现次数。
可以使用HashMap来计算一个字符串中每个字符出现的次数。具体实现如下:
import java.util.HashMap;
import java.util.Map;
public class CountCharacters {
public static void main(String[] args) {
String str = "hello world";
Map<Character, Integer> charCount = new HashMap<>();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (charCount.containsKey(c)) {
charCount.put(c, charCount.get(c) + 1);
} else {
charCount.put(c, 1);
}
}
for (Map.Entry<Character, Integer> entry : charCount.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
在这个例子中,我们首先创建一个空的HashMap来存储字符和它们出现的次数。然后遍历字符串中的每个字符,如果该字符已经在HashMap中存在,则将它的计数器加1;否则将它添加到HashMap中并设置计数器为1。最后遍历HashMap并输出每个字符及其出现次数
原文地址: https://www.cveoy.top/t/topic/ffhb 著作权归作者所有。请勿转载和采集!