【C++】提示并输入一个字符串,统计该字符串中字母个数、数字个数、空格个数、其他字符的个数

1、提示并输入一个字符串,统计该字符串中字母个数、数字个数、空格个数、其他字符的个数

        only只是一个简单的小练习

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string str;                //定义一个字符串类型
    cout<<"请输入一个字符串:";
    getline(cin,str);          //使用getline函数能够输入含有空格的字符串

    int len = str.length();
    //分别用来统计字符串中:字母,数字,空格,其他字符的个数,如果有就加1
    int letters = 0,digits = 0,spaces = 0,others = 0;

    for(int i = 0;i < len;i++)
    {
        char ch = str[i];    //定义一个字符类型接收str字符串里的每一个字符,进行判断

        //判断是否为字母
        if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
        {
            letters++;
        }

        //判断是否为数字
        else if(ch >= '0' && ch <= '9')
        {
            digits++;
        }

        //判断是否为空格
        else if(ch == ' ')
        {
            spaces++;
        }

        //如果以上都不是,那就说明是别的字符
        else
        {
            others++;
        }
    }

    //输出统计出的结果
    cout<<"该字符串中字母有:"<<letters<<"个"<<endl;
    cout<<"该字符串中数字有:"<<digits<<"个"<<endl;
    cout<<"该字符串中空格有:"<<spaces<<"个"<<endl;
    cout<<"该字符串中其它字符有:"<<others<<"个"<<endl;
}

输出结果如下:

补充:

#include <iostream>
#include <ctype.h>

using namespace std;

int main()
{
    string str;

    int alpha = 0;
    int digit = 0;
    int space = 0;
    int other = 0;

    cout<<"请输入一个字符串:";
    getline(cin, str);

    for(unsigned int i = 0; i < str.size(); i++)
    {
        if( isalpha(str.at(i)) )
        {
            alpha++;
        }else if( isdigit(str[i]) )
        {
            digit++;
        }else if(isspace(str.at(i)))
        {
            space++;
        }else
        {
            other++;
        }
    }

    cout<<"alpha = "<<alpha<<"  digit = "<<digit<<" space = "<<space<<" other = "<<other<<endl;

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值