牛客网 - 在线编程 - 华为机试 - 不同字符统计

题目描述
输入一行字符,分别统计出包含英文字母、空格、数字和其它字符的个数。

输入描述:

输入一行字符串,可以有空格

输出描述:

统计其中英文字符,空格字符,数字字符,其他字符的个数

示例1
输入

1qazxsw23 edcvfr45tgbn hy67uj m,ki89ol.\/;p0-=\][

输出

26
3
10
12

C++:

#include<iostream>
#include<string>
using namespace std;

int main()
{
    string s;
    while(getline(cin, s))
    {
        int count[4] = {0};
        for(int i = 0; i < s.size(); i++)
        {
            if (s[i] >= 'a' && s[i] <= 'z' || s[i] >= 'A' && s[i] <= 'Z')
            {
                count[0]++;                
            }
            else if(s[i] == ' ')
            {
                count[1]++;
            }
            else if(s[i] >= '0' && s[i] <= '9')
            {
                count[2]++;
            }
            else
            {
                count[3]++;
            }
        }
        for(int i = 0; i < 4; i++)
        {
            cout << count[i] << endl;
        }

    }
    return 0;
}

Python:

while True:
    try:
        a = input()
        count = [0,0,0,0]
        for i in a:
            if i.isalpha():
                count[0] += 1
            elif i.isspace():
                count[1] += 1
            elif i.isdigit():
                count[2] += 1
            else:
                count[3] += 1
        for i in count:
            print (i)
    except:
        break

猜你喜欢

转载自blog.csdn.net/qq_39735236/article/details/82155619