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

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

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

可以使用C++ string 内置函数实现

#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 (int i=0;i<=str.length();i++){
        if (isalpha(str[i])){
            chars++;
            continue;
        }
        if (isdigit(str[i])){
            digits++;
            continue;
        }
        if (isspace(str[i])){
            whitespace++;
            continue;
        }
        else{
            others++;
            continue;
        }
    }

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

    return 0;
}
全部评论

相关推荐

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

创作者周榜

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