用c++编写输入一个字符串统计其中数字字母空格和其他字符的程序

如题所述

第1个回答  2012-06-17
大致算法是:
cin 得到标准 string 字符串 str;
从 index=0 开始到 index=str.size() 依次扫描 str[index];
判断 str[index] 的 ASCII 码:
65~90 ('A'-'Z') 为大写字母,
97~122 ('a'-'z') 位小写字母,
32 (' ') 为空格,
48~57 ('0'-'9') 为数字,
剩下的为其他字符;
每个判断条件后跟一个自加1的变量, 最后变量的值就是统计结果.
第2个回答  2012-06-17
#include<iostream>
#include<string>
using namespace std;

int main()
{
int i = 0;
int a = 0, b = 0, c = 0, d = 0;
char str[100];
cout<<"请输入字符串"<<endl;
gets(str);
while(str[i] != '\0')
{
if(str[i] >= 'a' && str[i] <= 'z'
|| str[i] >= 'A' && str[i] <= 'Z')
a++;
else if(str[i] >= '0' && str[i] <= '9')
b++;
else if(str[i] = 32)
c++;
else
d++;
i++;
}
cout<<"字母有"<<a<<endl
<<"数字有"<<b<<endl
<<"空格有"<<c<<endl
<<"其他有"<<d<<endl;
}本回答被网友采纳
第3个回答  2012-06-17
void CountChars(const char* pStr)
{
int iSumDigtal=0; // 数字
int iSumAlpha=0; // 字母
int iSumSpace=0; // 空格
int iSumOther=0; // 其他
while(*pStr!='\0')
{
if(*pStr >='0' && *pStr <='9')iSumDigtal++;
else if(*pStr >='A' && *pStr <='z')iSumAlpha++;
else if(*pStr ==' ')iSumSpace++;
else iSumOther++;
pStr ++;
}
printf("数字个数%d\n",iSumDigtal);
printf("字母个数%d\n",iSumAlpha);
printf("空格个数%d\n",iSumSpace);
printf("其他个数%d\n",iSumOther);
}本回答被提问者采纳

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网