用hashmap查询字符串中各字符出现的次数
时间: 2023-11-28 13:04:33 浏览: 30
好的,可以使用 HashMap 来记录每个字符出现的次数。具体步骤如下:
1. 创建一个 HashMap 对象,用来存储每个字符和它出现的次数。
```
HashMap<Character, Integer> map = new HashMap<>();
```
2. 遍历字符串中的每个字符,如果该字符已经在 HashMap 中,则将该字符的计数器加 1,否则将该字符添加到 HashMap 中,并将计数器初始化为 1。
```
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);
}
}
```
3. 遍历 HashMap,输出每个字符以及它出现的次数。
```
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + "出现了" + entry.getValue() + "次");
}
```
完整代码如下:
```
public class Main {
public static void main(String[] args) {
String str = "hello world";
HashMap<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() + "次");
}
}
}
```
输出结果为:
```
空格出现了1次
d出现了1次
e出现了1次
h出现了1次
l出现了3次
o出现了2次
r出现了1次
w出现了1次
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)