写一个函数,由实参传来一个字符串,统计此字符串中字母、数字、空格和其他字符的个数,在主函数中输入字符串以及输出上述的结果。
void stat(char *str)
{
int n1,n2,n3,n4;
n1 = n2 = n3 = n4 = 0;
while (*str)
{
if ((*str >= 'a' && *str = 'A' && *str = '0' && *str <= '9')
n2++;
else if (*str == ' ')
n3++;
else n4++;
str++;
}
printf("the string has %d letters, %d numbers, %d spaces and %d other characters。
\n", n1, n2, n3, n4);
}
void main()
{
char str[51];
printf("please enter the string (no more than 50 characters): ");
scanf("%[^\n]", str); //仅当回车时才读入整个字符串,如果用%s则会在遇到空格时就读入字符串了。
stat(str);
}
。
对楼上的略作修改:
#include
#include
void stat(char *str)
{
int n1,n2,n3,n4;
n1 = n2 = n3 = n4 = 0;
while (*str!='\0')
{
if ((*str >= 'a' && *str = 'A' && *str = '0' && *str <= '9')
n2++;
else if (*str == ' ')
n3++;
else n4++;
str++;
}
printf("the string has %d letters, %d numbers, %d spaces and %d other characters。
\n", n1, n2, n3, n4);
}
void main()
{
char str[51];
clrscr();
printf("please enter the string (no more than 50 characters): \n");
gets(str);
stat(str);
getch();
}
。
。
#include "stdio。h"
#include "ctype。
h"
main()
{
char c[256]="grw etG&&HG&^(*&^&( 9 8 7 86Hrtghh";
register int i;
int a=0,n=0,s=0,o=0;
for(i=0;i<256;i++)
{
if(c[i]=='\0')
i=256;
if(isalpha(c[i]))
a++;
else if(isdigit(c[i]))
n++;
else if(isspace(c[i]))
s++;
else
o++;
}
printf("Alpha:\t%d\nNumber:\t%d\nSpace:\t%d\nOthers:\t%d\n",a,n,s,o);
}。