统计字符串出现的次数
时间: 2023-07-25 16:03:30 浏览: 44
可以使用 Python 中的字典来统计字符串中每个字符出现的次数,具体实现可以参考下面的代码:
```python
def count_chars(s):
char_dict = {}
for char in s:
if char in char_dict:
char_dict[char] += 1
else:
char_dict[char] = 1
return char_dict
```
该函数接受一个字符串作为参数,返回一个字典,其中每个键表示字符串中的一个字符,对应的值表示该字符在字符串中出现的次数。例如,对于字符串 "hello world",调用该函数会返回以下字典:
```python
{'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}
```
可以看到,字典中每个键表示字符串中的一个字符,对应的值表示该字符在字符串中出现的次数。
相关问题
js统计字符串出现次数
可以使用正则表达式和match()函数来实现统计字符串出现次数。
假设字符串为str,要统计的子字符串为subStr,可以使用以下代码:
```
var count = (str.match(new RegExp(subStr, "g")) || []).length;
```
这里用到了正则表达式,new RegExp(subStr, "g") 表示创建一个全局匹配子字符串的正则表达式,再使用match()函数返回一个数组,数组中包含所有匹配的字符串,统计其长度即可得到出现次数。
如果要忽略大小写,可以在正则表达式中加入"i"标志,如下所示:
```
var count = (str.match(new RegExp(subStr, "gi")) || []).length;
```
C语言统计字符串出现次数
以下是两种C语言统计字符串中各个字符出现次数的方法:
1.使用数组统计字符出现次数
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
int i, num[256] = {0};
printf("请输入字符串:");
scanf("%s", str);
for (i = 0; i < strlen(str); i++) {
num[(int)str[i]]++;
}
for (i = 0; i < 256; i++) {
if (num[i] != 0) {
printf("字符%c出现%d次\n", (char)i, num[i]);
}
}
return 0;
}
```
2.使用计数器统计字符出现次数
```c
#include <stdio.h>
int main() {
char str[200];
int cnt[128] = {0};
int i;
printf("请输入字符串:");
gets(str);
for (i = 0; str[i] != '\0'; ++i) {
cnt[str[i]]++;
}
for (i = 0; i < 128; i++) {
if (cnt[i] != 0) {
printf("%c:%d\n", i, cnt[i]);
}
}
return 0;
}
```
相关推荐
![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)