1218 - C语言8.21
编写一个函数,由实参传来一个字符串,统计这个字符串中字母、数字、空格和其他字符的个数。在主函数中输入字符串,并在主函数中输出上述结果。
Input
一行字符,可能包含空格。保证字符串的长度不超过100。
Output
分别输出这行字符中的英文字母、空格、数字和其他字符的个数,用空格隔开。
请注意行尾输出换行。
Examples
Input
What are you doing? 123456
Output
15 6 4 1
Solution C
#include<stdio.h> #include<string.h> int main() { char s[102]; int i,a,b,c,d,l; gets(s); l=strlen(s); a=b=c=d=0; for(i=0;i<l;i++) { if((s[i]>='a'&&s[i]<='z')||(s[i]>='A'&&s[i]<='Z')) a++; else if(s[i]>='0'&&s[i]<='9') b++; else if(s[i]==' ') c++; else d++; } printf("%d %d %d %d\n",a,b,c,d); return 0; }
Solution C++
#include <stdio.h> int main() { void calc(char str[], int *letter, int *digit, int *space, int *other); char str[101]; int letter, digit, space, other; gets(str); calc(str, &letter, &digit, &space, &other); printf("%d %d %d %d\n", letter, digit, space, other); return 0; } void calc(char str[], int *letter, int *digit, int *space, int *other) { int i; char c; *letter = 0; *space = 0; *digit = 0; *other = 0; for (i = 0;str[i] != '\0';i++) { c = str[i]; if (('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z')) (*letter)++; else if ('0' <= c && c <= '9') (*digit)++; else if (c == ' ') (*space)++; else (*other)++; } }