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;
}
“for(j = 0; str[i][j]; j++)”這一句沒有限制條件吧!是不是應(yīng)該寫成“for(j=0;str[i][j]!='\0';j++)”?
str[i][j]跟str[i][j]!='\0'是一樣的。C語言以非0為真,0為假,字符串以'\0'為結(jié)束標(biāo)志,'\0'實際上就是數(shù)字0。str[i][j]這種形式在C語言中是很普遍的。
聯(lián)系客服