c++求输入各种字符的个数

任务描述:

输入一行文字,找出其中的大写字母、小写字母、空格、数字以及其他字符各有多少(要求用指针或引用方法处理)。

测试输入:

abcJK 116_

预期输出:

upper case:2

lower case:3

space:1

digit:3

other:1

程序源码:

#include <stdio.h>
#include <iostream>
#include <string.h>
using namespace std;

void cal_str(string a)
{
    int upper=0,lower=0,space=0,digit=0,other=0;
    for(int i=0;i<a.length();i++)    
    {
        if(a[i]>='A' && a[i]<='Z')    upper++;
            else if(a[i]>='a' && a[i]<='z')    lower++;
                else if(a[i] == ' ')    space++;
                    else if(a[i]>='0' && a[i]<='9')    digit++;
                        else other++;
    }
    cout<<"upper case:"<<upper<<endl;
    cout<<"lower case:"<<lower<<endl;
    cout<<"space:"<<space<<endl;
    cout<<"digit:"<<digit<<endl;
    cout<<"other:"<<other<<endl;
}
int main()
{
    
    // 请在此添加代码
    /********** Begin *********/
    string a;
    getline(cin,a);//string类中的函数  getline(cin, s);
    cal_str(a);
    
    
    /********** End **********/
    return 0;
}
原文地址:https://www.cnblogs.com/junfblog/p/12705580.html