分享

C语言编程 有一篇文章,共有3行文字,每行80个字符。要求分别统计出其中英文字母,数字,空...

 昵称7241419 2011-06-29
2种做法,1种用单字符来读取输入,1种用字符串来读取输入。
1.
#include <stdio.h>

int main()
{
int i, upper, lower, digit, space, other;
char c;
upper = lower = digit = space = other = 0;
for(i = 0; i < 3; i++)
while((c = getchar()) != '\n')
if('A' <= c && c <= 'Z')
upper++;
else if('a' <= c && c <= 'z')
lower++;
else if('0' <= c && c <= '9')
digit++;
else if(c == ' ')
space++;
else
other++;
printf("upper:%d\nlower:%d\ndigit:%d\nspace:%d\nother:%d\n", upper, lower, digit, space, other);
return 0;
}

2.
#include <stdio.h>

int main()
{
int i, j, upper, lower, digit, space, other;
char str[3][81];
upper = lower = digit = space = other = 0;
for(i = 0; i < 3; i++)
{
gets(str[i]);
for(j = 0; str[i][j]; j++)
if('A' <= str[i][j] && str[i][j] <= 'Z')
upper++;
else if('a' <= str[i][j] && str[i][j] <= 'z')
lower++;
else if('0' <= str[i][j] && str[i][j] <= '9')
digit++;
else if(str[i][j] == ' ')
space++;
else
other++;
}
printf("upper:%d\nlower:%d\ndigit:%d\nspace:%d\nother:%d\n", upper, lower, digit, space, other);
return 0;
}
提问人的追问   2009-05-02 11:48
“for(j = 0; str[i][j]; j++)”这一句没有限制条件吧!是不是应该写成“for(j=0;str[i][j]!='\0';j++)”?
回答人的补充   2009-05-02 12:04
str[i][j]跟str[i][j]!='\0'是一样的。C语言以非0为真,0为假,字符串以'\0'为结束标志,'\0'实际上就是数字0。str[i][j]这种形式在C语言中是很普遍的。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多