统计字符串中不同字符出现的次数(频率)

系列文章目录

前言

《数据结构基础》c语言版 第2版,Ellis Horowitz著,朱仲涛译
2.7节,page77,习题1

一、题目描述

编写函数,读入一个字符串,统计字符串中不同字符的出现频率。

二、c++代码

1.方法1

代码如下:

#include<iostream>
#include <string.h>
#include <map>
using namespace std;

int main() {
    string str="abcaaabbabc";
    map<char,int>m;
    for(auto &i:str)
        m[i]++;
    for(auto &i:m)
        printf("%c" " " "%d\n",i.first,i.second);
    system("pause");
    return 0;
}

添加链接描述

添加链接描述

2.方法2

思路:先创建一个map,遍历字符串,逐个判断如果存在则count++,不存在则创建一个,让其value为1

代码如下:

#include<iostream>
#include <map>
using namespace std;

int main() {
    string str="abcabcacab";
    map<char,int>m;
    for(int i=0;i<str.length();i++)
    {
        map<char,int>::iterator iter = m.find(str[i]);
        if(iter!=m.end())
        {
            iter->second++;
        } else
        {
            m.insert(pair<char,int>(str[i],1));
        }
    }

    map<char,int>::iterator iter=m.begin();
    for( ;iter!=m.end();iter++)
        printf("%c" " " "%2d\n",iter->first,iter->second);

    system("pause");
    return 0;
}

map学习:
添加链接描述

2.方法3

思路:通过插入失败来增加字符的个数,如果插入失败则表明map中存在该字符,count++即可

代码如下:

#include<iostream>
#include <map>
using namespace std;

int main() {
    string str = "abcabcacab";
    map<char, int> m;
    pair<map<char, int>::iterator, bool> result;

    for (int i = 0; i < str.length(); i++) {
        result = m.insert(pair<char, int>(str[i], 1));
        if (result.second == false)
            result.first->second++;
    }
        map<char, int>::iterator iter = m.begin();
        for (; iter != m.end(); iter++)
            printf("%c" " " "%2d\n", iter->first, iter->second);

        system("pause");
        return 0;
}

总结

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 使用Python统计字符串数字出现次数的代码如下: ```python s = 'ab12cd34ef56' count = 0 for c in s: if c.isdigit(): count += 1 print(count) ``` 输出结果为:6 如果字符串存在小数或负数,需要修改代码的 `isdigit()` 方法为更为通用的正则表达式匹配方法。 ### 回答2: Python 统计字符串数字出现次数可以通过正则表达式、遍历字符串以及通过 Counter 类进行统计实现。 1. 正则表达式 使用正则表达式可以快速地匹配出字符串所有数字,并进行统计。Python 的 re 模块提供了很好的正则表达式支持。实现代码如下: ```python import re s = 'ab123cd456ef78' nums = re.findall('\d+', s) count = len(nums) print(nums) print(count) ``` 输出结果为: ``` ['123', '456', '78'] 3 ``` 其 '\d+' 表示匹配一个或多个数字,findall 函数会返回所有匹配的数字列表,并通过 len 函数计算出数字出现次数。 2. 遍历字符串 如果不使用正则表达式,我们也可以通过遍历字符串统计数字出现次数。实现代码如下: ```python s = 'ab123cd456ef78' count = 0 for i in s: if i.isdigit(): count += 1 print(count) ``` 输出结果为: ``` 7 ``` 遍历字符串的每个字符,通过 isdigit 方法判断是否为数字,如果是则计数器加一。 3. 使用 Counter 类 Python 的 collections 模块提供了很多有用的工具类,其 Counter 类可以实现对元素频率统计。实现代码如下: ```python from collections import Counter s = 'ab123cd456ef78' nums = [int(i) for i in s if i.isdigit()] count = Counter(nums) print(count) ``` 输出结果为: ``` Counter({3: 2, 1: 1, 2: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1}) ``` 首先通过列表推导式从字符串提取出所有数字,并使用 int 函数将其转换为整型。然后使用 Counter 函数统计数字出现频率,得到一个字典形式的计数结果。如果只需要统计数量,可以使用 sum 函数对计数结果的 values 进行求和。 ### 回答3: Python是一门非常强大的编程语言,可以帮助我们完成很多实用的任务。在这里,我们来探讨一下如何用Python统计字符串数字出现次数。 首先,我们需要知道Python字符串是由一系列字符组成的,而在这些字符可能包含数字。我们的任务就是找出字符串所有的数字,并统计它们出现次数。 为了完成这个任务,我们可以使用Python的正则表达式。正则表达式是一种特殊的语法,用于描述一定规则的字符串模式。在Python,我们可以使用re模块来操作正则表达式。 下面是一个使用Python统计字符串数字出现次数的示例代码: ``` import re def count_digits(s): # 定义正则表达式匹配数字 pattern = r'\d' # 使用findall函数查找字符串所有匹配的数字 digits = re.findall(pattern, s) # 统计数字出现次数 counts = {} for digit in digits: if digit in counts: counts[digit] += 1 else: counts[digit] = 1 # 返回结果 return counts # 测试 s = "hello 123 world 456" counts = count_digits(s) print(counts) ``` 在这个示例代码,我们首先导入了Python的re模块。接着,定义了一个名为count_digits的函数,该函数接受一个字符串作为参数。在函数,我们定义了一个正则表达式pattern,用于匹配字符串的数字。然后,使用re模块的findall函数,在字符串查找所有匹配的数字,并将其保存在一个名为digits的列表。接下来,我们使用一个循环来遍历列表的每个数字,并统计它们出现次数。最后,返回一个字典,其包含数字及其出现次数。 最后,我们测试了一下我们的函数,输入了一个包含数字的字符串,打印出了每个数字出现次数。结果如下: ``` {'1': 1, '2': 1, '3': 1, '4': 1, '5': 1, '6': 1} ``` 可以看到,我们的函数成功地统计字符串所有数字的出现次数

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值