如何编写一个C ++程序,它计算输入字符串中的大写字母,小写字母和整数的数量? [英] How to code a C++ program which counts the number of uppercase letters, lowercase letters and integers in an inputted string?

查看:746
本文介绍了如何编写一个C ++程序,它计算输入字符串中的大写字母,小写字母和整数的数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个简单的基本方式(理想的初学者学习最简单的方法)在C ++编写一个程序,从用户获取一个字符串,并输出大写字母,小写字母和整数(数字)。我很喜欢使用C ++语法的业余,所以请帮助我一个易于理解的语法。谢谢!

I'm looking for a simple and basic way (ideal for beginners to learn the easiest way) to write a program in C++ which gets a string from the user and outputs the number of uppercase letters, lowercase letters and integers (numbers). I'm pretty amateur at using C++ syntax so please help me with an easy-to-understand syntax. Thanks!

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

Here is a very simple code that I found in Google and did some changes and corrections:

#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,对吧?我们如何改变它,所以我们可以在字符串中有空格?

So in this code; we are assuming that the end of a string has the integer 0, right? How can we change it so we can have spaces in the string?

推荐答案

#include<stdio.h>
main() 
{
int upper = 0, lower = 0,digit=0,special=0;
char ch[80];
int i;

printf("\nEnter The String : ");
gets(ch);

for(i = 0; ch[i]!='\0';i++)

{
if (ch[i] >= 'A' && ch[i] <= 'Z')
upper++;
else if (ch[i] >= 'a' && ch[i] <= 'z')
lower++;
else if(ch[i] >='0' && ch[i] <='9')
digit++;
else if(ch[i]!=' ')
special++;
}


printf("\nUppercase Letters : %d", upper);
printf("\nLowercase Letters : %d", lower);
printf("\nDigits : %d", digit);
printf("\nSpecial Characters : %d",special);
}

这篇关于如何编写一个C ++程序,它计算输入字符串中的大写字母,小写字母和整数的数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆