题解 | 使用字符函数统计字符串中各类型字符的个数

使用字符函数统计字符串中各类型字符的个数

https://www.nowcoder.com/practice/31bdbc70188f48e995fa3cbef36613c8

#include <iostream>
#include <string>

using namespace std;

#include <cctype>//字符处理函数的头文件


//函数模板
template <typename Pred>
int count_if_match(const string &str,Pred p)
{
    int count = 0;
    for(char c : str)//范围for
    {
        if(p(static_cast <unsigned char>(c)))
        {
            count++;
        }
    }

    return count;
}

int main() {

    string str;
    getline(cin, str);

    int whitespace = 0;
    int digits = 0;
    int chars = 0;
    int others = 0;

    // write your code here......
    chars = count_if_match(str,::isalpha);

    whitespace = count_if_match(str,::isspace);

    digits = count_if_match(str,::isdigit);

    others = str.length() - chars - whitespace - digits;

    cout << "chars : " << chars
        << " whitespace : " << whitespace
        << " digits : " << digits
        << " others : " << others << endl;

    return 0;
}

全部评论
函数模板、范围for、库函数
点赞 回复 分享
发布于 2025-12-31 11:55 江西

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务