文档库 最新最全的文档下载
当前位置:文档库 › 编写函数,统计一个字符串中字母、数字、空格的个数。

编写函数,统计一个字符串中字母、数字、空格的个数。

//1. 编写函数,统计一个字符串中字母、数字、空格的个数。在主函数中调用并输出统计结果(用指针完成)。
方法一
#include
#include
void count(char *s, int *a, int *b, int *c, int *d)
{
*a = *b = *c = *d = 0;
while(*s)
{
if('A' <= *s && *s <= 'Z' || 'a' <= *s && *s <= 'z')
(*a)++;
else if('0' <= *s && *s <= '9')
(*b)++;
else if(*s == ' ')
(*c)++;
else
(*d)++;
s++;
}
}
main()
{
char s[100];
int lc, dc, sc, oc;
printf("输入字符串:\n");
gets(s);
count(s, &lc, &dc, &sc, &oc);
printf("字母:%d\n", lc);
printf("数字:%d\n", dc);
printf("空格:%d\n", sc);
printf("其它:%d\n", oc);
return 0;
}
方法二
#include
#include
/*统计函数*/
void check(char *str)
{
int i,number=0,space=0,zimu=0,other=0;
char *p=str;
for(i=0;i{
if(*(p+i)>='0' && *(p+i)<='9') /*数字*/
number++;
else if(*(p+i) == 32) /*空格*/
space++;
else if((*(p+i)>='a' && *(p+i)<='z')||(*(p+i)>='A' && *(p+i)<='Z'))
zimu++;/*其它字符*/
else other++;
}
printf("%s\n",str);
printf("number:%d\nspace:%d\nzimu:%d\nother char:%d\n",number,space,zimu,other);
}
/*主函数*/
main()
{
char string[100];
gets(string); /*输入字符串,因为要包括空格,不能用scanf()*/
check(string); /*调用函数*/
}

相关文档