C++ 数组 输入一行字符串(长度小于80个字符,只有字母和数字),统计其中大写字母、小写字母和数字的个数

如题所述

第1个回答  2022-11-16

源程序代码以及算法解释如下:

#define _CRT_SECURE_NO_WARNINGS//VS环境下需要,VC不需要

#include <iostream> 

#include <string>

int main()

{

 const int n = 80;

 int i = 0;

 char str[n] = { NULL };//字符数组

 int Numb_count = 0;//数字个数

 int ABC_count = 0;//大写字母个数

 int abc_count = 0;//小写字母个数

 scanf("%s", str);//连续输入字符到字符数组

 while (str[i] != '\0')

 {

  if ((str[i] >= '0') && (str[i] <= '9'))//判断是否是数字     

  {

   Numb_count++;

  }

  else if ((str[i] >= 'a') && (str[i] <= 'z'))//判断是否是小写字母 

  {

   abc_count++;

  }

  else if ((str[i] >= 'A') && (str[i] <= 'Z'))//判断是否是大写字母

  {

   ABC_count++;

  }

  i++;

 }

 printf("数字个数:%d\n小写字母个数:%d\n大写字母个数:%d\n", Numb_count, abc_count, ABC_count);

 return 0;

}

程序运行结果如下:



扩展资料:

其他实现方式:

#include "stdafx.h"

#include <iostream>

int main()

{

char str[80]="\0",resultStr[80]="\0";

int cursor=0;

printf("请输入字符串:");

scanf("%s",str);

char *tempStr = str;

while (*tempStr != '\0')

{

char ch = *tempStr;

if ((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z'))

{

resultStr[cursor] = ch;

cursor++;

}

tempStr++;

}

printf("输入字符为:%s\n输出字符为:%s\n",str,resultStr);

system("pause");

return 0;

}



相似回答