編寫一個函數,由實參傳來一個字符串,統計此字符串中字母、數字、空格和其他字符的個數,在主函數中輸人字符串以及輸出上述的結果
題目解析:
該題的關鍵在於要能夠寫出各種字符統計的條件
代碼示例:
#include<stdio.h>
int letter, digit, space, others;
void CountChar(char str[])
{
int i;
for (i = 0; str[i] != '\0'; i++)
{
//統計字母
if ((str[i] >= 'a'&& str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z'))
letter++;
else if (str[i] >= '0' && str[i] <= '9') //統計數字
digit++;
else if (str[i] == ' ')//統計空格
space++;
else
others++; //統計其他字符
}
}
int main()
{
char text[80];
printf("input string:\n");
gets(text);
printf("string: %s\n", text);
CountChar(text);
printf("\nletter:%d\ndigit:%d\nspace:%d\nothers:%d\n", letter, digit, space, others);
return 0;
}