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

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

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

#include <iostream>
#include <string>

using namespace std;

int main() {

    string str;
    getline(cin, str);

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

    // write your code here......
    for (auto a: str)
    {
        if (a >= '0' && a <= '9')
            ++digits;
        else if ((a >= 'a' && a <='z') || (a >= 'A' && a <= 'Z'))
            ++chars;
        else if (a == ' ')
            ++whitespace;
        else
            ++others; 
    }

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

    return 0;
}

使用范围for循环。范围for循环等价于:

char* str_point = &str[0];
while(*str_point != '\0')
{
        if (*str_point >= '0' && *str_point <= '9')
            ++digits;
        else if ((*str_point >= 'a' && *str_point <='z') || (*str_point >= 'A' && *str_point <= 'Z'))
            ++chars;
        else if (*str_point == ' ')
            ++whitespace;
        else
            ++others;
        str_point++;
}

C++题解 文章被收录于专栏

记录在牛客网用C++刷题的题解思路

全部评论

相关推荐

07-14 12:29
门头沟学院 Java
后端岗,实习三周感觉有点想跑路了,担心秋招被拉黑,有没有佬是字节HR知道情况的
从零开始的转码生活:你实习三周都想跑路,将来拿到offer真的愿意在这干十几二十年吗
投递字节跳动等公司8个岗位
点赞 评论 收藏
分享
吴offer选手:HR:我KPI到手了就行,合不合适关我什么事
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-10 14:10
啊啊啊啊好幸福,妈妈是我找工作发疯前的一束光
黑皮白袜臭脚体育生:看了这篇帖子之后已经第一百次质问老妈,仍然没有得到我的老妈是老板的回答
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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