1218 - C语言8.21
时间限制 : 1 秒
内存限制 : 32 MB
编写一个函数,由实参传来一个字符串,统计这个字符串中字母、数字、空格和其他字符的个数。在主函数中输入字符串,并在主函数中输出上述结果。
题目输入
一行字符,可能包含空格。保证字符串的长度不超过100。
题目输出
分别输出这行字符中的英文字母、空格、数字和其他字符的个数,用空格隔开。
请注意行尾输出换行。
输入/输出样例
输入格式
What are you doing? 123456
输出格式
15 6 4 1
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; }
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)++; } }
Java解答
import java.util.Scanner; public class Main { private static Scanner s = new Scanner(System.in) ; public static void main(String[] args) { String str = s.nextLine() ; char[]c = str.toCharArray() ; int a = 0 ; int b = 0 ; int d = 0 ; int e = 0 ; int f = 0 ; for (int i = 0; i < c.length; i++) { if('A'<=c[i]&&c[i]<='Z'){ a++ ; } else if('a'<=c[i]&&c[i]<='z'){ a++ ; } else if(c[i]==' '){ d++ ; } else if('0'<=c[i]&&c[i]<='9'){ e++ ; }else f++ ; } System.out.println(a+" "+e+" "+d+" "+f) ; } }