You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

已实现无库函数版本,如何用C++字符串库函数统计数字并替换字母为空格?

C++字符串库函数实现数字统计与字母替换

我们需要实现两个核心功能:

  • 统计字符串中0-9每个数字的出现次数
  • 将字符串中所有字母(大小写)替换为空格

你已经完成了原生方式的实现,下面是用C++标准库相关函数完成的版本,同时附上修正后的原生实现代码:

原生实现代码(修正细节)

#include <iostream>
#include <string>

using namespace std;

void without_functions(string str)
{
    int* how_many_num = new int[10];
    for (int i = 0; i < 10; ++i)
        how_many_num[i] = 0;

    for (int i = 0; i < str.size(); ++i)
    {
        if (str[i] >= '0' && str[i] <= '9')
        {
            ++how_many_num[int(str[i]) - 48];
        }
    }

    for (int i = 0; i <= 9; ++i)
    {
        if (how_many_num[i] != 0)
        {
            cout << "Digit " << i << " is found " << how_many_num[i] << " times" << endl;
        }
    }
   
    for (int i = 0; i < str.size(); ++i)
    {
        // 修正原代码的字符判断错误,直接用字母范围更直观
        if ((str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= 'a' && str[i] <= 'z'))
        {
            str[i] = ' ';
        }
    }

    cout << endl << "New string:  " << str << endl;
    delete[] how_many_num; // 补充内存释放,避免泄漏
}

标准库函数实现版本

#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>

void with_functions(std::string str)
{
    // 统计每个数字出现次数
    int how_many_num[10] = {0};
    for (int i = 0; i < 10; ++i)
    {
        char target_digit = '0' + i;
        // 使用std::count统计指定数字的出现次数
        how_many_num[i] = std::count(str.begin(), str.end(), target_digit);
    }

    // 输出统计结果
    for (int i = 0; i < 10; ++i)
    {
        if (how_many_num[i] != 0)
        {
            std::cout << "Digit " << i << " is found " << how_many_num[i] << " times" << std::endl;
        }
    }

    // 使用std::replace_if替换所有字母为空格
    std::replace_if(str.begin(), str.end(), 
        [](char c) {
            // 用std::isalpha判断是否为字母,强制转unsigned char避免未定义行为
            return std::isalpha(static_cast<unsigned char>(c));
        }, 
        ' ');

    std::cout << std::endl << "New string:  " << str << std::endl;
}

关键库函数说明

  • std::count:来自<algorithm>头文件,直接统计指定范围内目标元素的出现次数,替代原生循环的逐个判断计数逻辑。
  • std::replace_if:同样来自<algorithm>,遍历字符串范围,对满足lambda条件的字符执行替换操作。
  • std::isalpha:来自<cctype>头文件,用于判断字符是否为字母,配合static_cast<unsigned char>避免处理负数字符时的未定义行为。

内容的提问来源于stack exchange,提问作者Ianna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 00:40:42