如何编写一个C++程序来计算输入字符串中的大写字母,小写字母和整数的数量?

Sep*_*ent -5 c++ string counting lowercase uppercase

我正在寻找一种简单而基本的方法(非常适合初学者学习最简单的方法)用C++编写程序,该程序从用户获取字符串并输出大写字母,小写字母和整数(数字)的数量.我非常喜欢使用C++语法,所以请用一种易于理解的语法帮助我.谢谢!

编辑:这是一个非常简单的代码,我在谷歌找到并做了一些更改和更正:

#include <iostream>
#include <conio.h>
using namespace std;

int main()
{

   char array1[50];
   int i = 0, lowercase = 0, uppercase = 0, numbers = 0, total;

   cout << "Enter a string: "<<endl;
   cin >> array1;
   cout <<endl;

      while (array1[i] != 0){

         if(array1[i] >= 'a' && array1[i] <= 'z'){
         lowercase++;
         i++;
       }

         else if (array1[i] >= 'A' && array1[i] <= 'Z'){
         uppercase++;
         i++;
       }

         else if (array1[i] >= '0' && array1[i] <= '9'){
         numbers++;
         i++;
       }

         else
         i++;
    }

total = lowercase + uppercase + numbers;

cout << "Your string has " << lowercase << " lowercase letters." << endl;

cout << "Your string has " << uppercase << " uppercase letters." <<endl;

cout << "Your string has " << numbers << " numbers." <<endl;

cout << "Your string has " << total << " total characters." <<endl;


getch();

return 0;
}
Run Code Online (Sandbox Code Playgroud)

所以在这段代码中; 我们假设一个字符串的结尾有整数0,对吗?我们如何改变它,以便我们可以在字符串中有空格?

mns*_*hab 6

尝试:

#include <algorithm>
#include <iostream>
#include <cctype>
#include <string>

using namespace std;

int main()
{
    cout << " Enter text: ";
    string s;
    if(getline(cin, s))
    {
        size_t count_lower = count_if(s.begin(), s.end(), 
               [](unsigned char ch) { return islower(ch); });
        cout << "lowers: " << count_lower ;

        size_t count_upper = count_if(s.begin(), s.end(),    
               [](unsigned char ch) { return isupper(ch); });
        cout << "uppers: " << count_upper ;

        size_t count_digit = count_if(s.begin(), s.end(),    
               [](unsigned char ch) { return isdigit(ch); });
        cout << "digits: " << count_digit ;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 特别是考虑到这没有解释,并使用lambda表达式,我不确定它是否"易于新手使用/学习". (5认同)
  • @BradleyDotNET - 关于这个和*其他*提交,SO的一种传统是为家庭作业提供过于复杂和/或危险的解决方案,特别是如果OP没有在他身边尝试......;) (2认同)