java统计一个字符串中每个字符出现的次数
时间: 2023-09-25 14:15:26 浏览: 77
可以使用一个 HashMap 来统计每个字符出现的次数。遍历字符串,对于每个字符,如果它已经在 HashMap 中,则将其对应的计数器加一;否则,将其添加到 HashMap 中,并将计数器初始化为 1。最后遍历 HashMap,输出每个字符及其出现的次数。
以下是 Java 代码示例:
```java
import java.util.*;
public class CharacterCount {
public static void main(String[] args) {
String str = "hello world";
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (map.containsKey(c)) {
map.put(c, map.get(c) + 1);
} else {
map.put(c, 1);
}
}
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
```
输出结果为:
```
h: 1
e: 1
l: 3
o: 2
: 1
w: 1
r: 1
d: 1
```