怎么统计字符串中每个字符出现的次数
时间: 2023-09-24 22:09:43 浏览: 36
可以使用一个字典来记录每个字符出现的次数,遍历字符串的每个字符,如果该字符已经在字典中出现过,就将其对应的值加1,否则在字典中添加该字符并将其值设为1。
示例代码:
```python
str = "hello world"
char_count = {}
for char in str:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
print(char_count)
```
输出:
```
{'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}
```
其中,字典的键是字符,值是该字符出现的次数。
相关问题
java 统计字符串中每个字符出现次数
好的,这个问题可以回答。请参考以下 Java 代码:
```java
public static void countCharacters(String str) {
Map<Character, Integer> charCountMap = new LinkedHashMap<>();
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
int count = charCountMap.getOrDefault(ch, 0);
charCountMap.put(ch, count + 1);
}
for (Map.Entry<Character, Integer> entry : charCountMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
```
这个方法会统计一个字符串中每个字符出现的次数,并打印出来。您可以将需要统计的字符串作为参数传入该方法。
python统计字符串中每个字符出现次数,不用字典
可以使用列表来统计字符串中每个字符出现的次数,具体实现如下:
```python
s = "hello world"
counts = [0] * 256 # 初始化一个长度为256的列表,用于存储每个字符出现的次数
for c in s:
counts[ord(c)] += 1 # ord()函数将字符转换为ASCII码,用作列表的下标
for i in range(256):
if counts[i] != 0:
print(chr(i), counts[i]) # chr()函数将ASCII码转换为字符
```
这段代码的输出结果为:
```
h 1
e 1
l 3
o 2
1
w 1
r 1
d 1
```
这表示字符串中字符"h"出现了1次,字符"e"出现了1次,字符"l"出现了3次,以此类推。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.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_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)