统计每个字符出现的次数并打印到控制台。
时间: 2023-09-16 11:09:10 浏览: 44
假设要统计的字符串为str:
```
String str = "hello world";
```
可以使用Map来存储每个字符出现的次数,代码如下:
```
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (map.containsKey(c)) {
int count = map.get(c);
map.put(c, count + 1);
} else {
map.put(c, 1);
}
}
```
以上代码中,首先创建了一个Map对象用于存储字符和其出现次数的对应关系。然后遍历字符串中的每个字符,如果字符已经在Map中出现过,则将其出现次数加1;否则将其出现次数初始化为1并存入Map中。
最后可以通过遍历Map来打印每个字符出现的次数:
```
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
```
相关问题
js统计 一个字符串每个字母出现的次数
你可以使用 JavaScript 来统计一个字符串中每个字母出现的次数。以下是一个示例代码:
```javascript
function countLetters(str) {
let result = {};
for (let i = 0; i < str.length; i++) {
let letter = str[i];
// 如果字母已经在结果对象中,则递增计数
if (result[letter]) {
result[letter]++;
}
// 否则将字母添加到结果对象,并将计数设置为1
else {
result[letter] = 1;
}
}
return result;
}
let input = "hello world";
let letterCounts = countLetters(input);
console.log(letterCounts);
```
上述代码中,`countLetters` 函数接收一个字符串作为输入,并返回一个对象,其中包含每个字母作为键,对应的出现次数作为值。通过遍历字符串中的每个字符,我们判断该字符是否已经在结果对象中,如果是则递增计数,否则将该字符添加到结果对象并设置计数为1。最后,我们将结果对象打印到控制台。
在上述示例中,输入字符串是 "hello world",输出结果将是 `{ h: 1, e: 1, l: 3, o: 2, ' ': 1, w: 1, r: 1, d: 1 }`,表示每个字母出现的次数。
用js写统计字符串中每个字符出现的次数
以下是用JavaScript实现统计字符串中每个字符出现次数的代码:
```javascript
function countCharacters(str) {
let obj = {};
for(let i = 0; i < str.length; i++) {
let char = str.charAt(i);
if(obj[char]) {
obj[char]++;
} else {
obj[char] = 1;
}
}
return obj;
}
let str = "hello world";
let result = countCharacters(str);
console.log(result);
```
以上代码中,我们首先定义了一个countCharacters()函数来统计字符串中每个字符出现的次数。在函数中,我们使用一个obj对象来存储每个字符出现的次数。我们遍历字符串中的每个字符,并检查obj对象中是否存在该字符。如果存在,则将该字符的计数器加1;否则,在obj对象中添加该字符并将计数器初始化为1。最后,我们返回obj对象。
在上面的示例中,我们将字符串“hello world”传递给countCharacters()函数,并将返回的对象存储在result变量中。然后,我们使用console.log()函数将结果打印到控制台中。输出结果将是一个对象,其中每个键表示字符串中的一个字符,每个值表示该字符在字符串中出现的次数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.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)