指针练习--字符串统计
时间: 1ms 内存:128M
描述:
实现一个统计函数。统计字符串中大写字母、小写字母和其他字符的个数。
主函数已给定如下,提交时不需要包含下述主函数
int main()
{
char str[80];
int numA,numa,numt;
cin.getline(str,80);
count(str,&numA,&numa,&numt);
cout<<"大写字母个数为 "<<numA<<endl
<<"小写字母个数为 "<<numa<<endl
<<"其他字符个数为 "<<numt<<endl;
return 0;
}
输入:
一行字符串
输出:
大写字母、小写字母和其他字符的个数
示例输入:
WVGA:800*480,HDTV:1080i,33.75kHz
示例输出:
大写字母个数为 9
小写字母个数为 3
其他字符个数为 20
提示:
参考答案(内存最优[1092]):
#include<stdio.h>
int main()
{
char str[80];
int numA=0,numa=0,numt=0;
int i=0;
gets(str);
while(str[i]!='\0')
{
if(str[i]>='A'&&str[i]<='Z')
numA++;
else if(str[i]>='a'&&str[i]<='z')
numa++;
else
numt++;
i++;
}
printf("大写字母个数为 %d\n小写字母个数为 %d\n其他字符个数为 %d",numA,numa,numt);
/*cin.getline(str,80);
count(str,&numA,&numa,&numt);
cout<<"大写字母个数为 "<<numA<<endl
<<"小写字母个数为 "<<numa<<endl
<<"其他字符个数为 "<<numt<<endl;*/
return 0;
}
参考答案(时间最优[0]):
#include <iostream>
using namespace std;
void count(char *str, int *pnumA,int *pnuma,int *pnumt)
{
int i=0;
*pnumA=*pnuma=*pnumt=0;
while(str[i]!='\0')
{
if(str[i]>='A'&&str[i]<='Z') (*pnumA)++;
else if (str[i]>='a'&&str[i]<='z') (*pnuma)++;
else (*pnumt)++;
i++;
}
}
int main()
{
char str[80];
int numA,numa,numt;
cin.getline(str,80);
count(str,&numA,&numa,&numt);
cout<<"大写字母个数为 "<<numA<<endl
<<"小写字母个数为 "<<numa<<endl
<<"其他字符个数为 "<<numt<<endl;
return 0;
}
题目和答案均来自于互联网,仅供参考,如有问题请联系管理员修改或删除。