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

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

作者:互联网

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

编辑:
这是我在Google中找到的非常简单的代码,并进行了一些更改和更正:

#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;
}

所以在这段代码中;我们假设字符串的末尾具有整数0,对吧?我们如何更改它以便在字符串中保留空格?

解决方法:

尝试:

#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 ;
    }
}

标签:lowercase,counting,c,string,uppercase
来源: https://codeday.me/bug/20191010/1886418.html