分别统计出包含英文字母、空格、数字和其它字符的个数(HJ40)

一:解题思路

注意输入字符串str中,如果包含空格,则需要用getline(cin,str)

二:完整代码示例 (C++版和Java版)

C++代码:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string str = "";

    while (getline(cin,str))
    {
        int alphCounts = 0;
        int bankCounts = 0;
        int numberCounts = 0;
        int othersCounts = 0;

        for (int i = 0; i < str.length(); i++)
        {
            if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z'))
            {
                alphCounts++;
            }
            else if (str[i] == ' ')
            {
                bankCounts++;
            }
            else if (str[i] >= '0' && str[i] <= '9')
            {
                numberCounts++;
            }
            else
            {
                othersCounts++;
            }
        }

        cout << alphCounts << endl;
        cout << bankCounts << endl;
        cout << numberCounts << endl;
        cout << othersCounts << endl;
    }

    return 0;
}

 

posted @ 2020-08-05 17:00  repinkply  阅读(210)  评论(0)    收藏  举报