输入一行字符,分别统计出其中英文字母、空格、数字和其他字符的个数
*gets(a)函数的用法:这个函数很简单,只有一个参数。参数类型为 char 型,即 str 可以是一个字符指针变量名,也可以是一个字符数组名。c语言里gets(a) 表示输入一个字符串到数组a,a表示读取一个字符串存入a中,字符串输入结束标志为换行符。
*puts()函数的用法:*用来向标准输出设备(屏幕)输出字符串并换行,具体为:把字符串输出到标准输出设备,将’\0’转换为回车换行。其调用方式为,puts(s);其中s为字符串字符(字符串数组名或字符串指针)。
方法一:单个字符输入(常规做法)
# include<stdio.h> //getchar()是从键盘中读取字符,它一次接受一个字符;如果一次敲的字符多于一个,包括回车字符,它会将剩下的字符存入缓存中,下次继续执行。
void main()
{
char c;
int letter=0,space=0,digit=0,other=0;//计数器初始化为0
while(1){
printf("please input some characters:\n");
while((c=getchar())!='\n') //getchar()既可以输出单个字符也可以输出多个字符,循环读取字符,到换行结束。
{
if(c=='\n')
{break;}
if((c>='A'&& c<='Z')||(c>='a'&&c<='z'))
{letter++;}
else if(c>='0'&& c<='9')
{digit++;}
else if(c==' ')
{space++;}
else
{other++;}
}
printf("该行字符中字母数为:%d ,空格数为:%d ,数字数为:%d ,其他字符为:%d\n",letter,space,digit,other);
}
}
方法二:整个字符串输入
# include<stdio.h>
int main()
{
char c[100]; //定义数组类型char型
int i=0,letter=0,space=0,digit=0,other=0;
printf("请输入一行字符:");
gets(c);
while(c[i]!='\0')
{
if((c[i]>='A'&& c[i]<='Z')||(c[i]>='a'&&c[i]<='z'))
letter++;
else if(c[i]>='0'&& c[i]<='9')
digit++;
else if(c[i]==' ')
space++;
else
other++;
i++; //以此判断数组中的第几位
}
printf("该行字符中字母数为:%d ,空格数为:%d ,数字数为:%d ,其他字符为:%d\n",letters,space,digit,other);
return 0;
}
方法三:
引申:有一篇文章,共有3行文字,每行有80个字符。要求分别统计出其中英文大写字母、小写字母、数字、空格以及其他字符的个数。
代码如下:
#include<stdio.h>
int main()
{
char c[3][80];
int i,j,capital=0,lowercase=0,digit=0,space=0,other=0;
for(i=0; i<3; i++) {
printf("请输入第%d行字符:",i+1);
gets(c[i]); //等价于scanf("%s",&c[i])
}
for(i=0;i<3;i++)
{
for(j=0;j<80&&c[i][j]!='\0';j++) //两层循环嵌套统计三行字符串中各元素数目
{
if(c[i][j]==' ')space++;
else if((c[i][j]>='0')&&(c[i][j]<='9'))
digit++;
else if((c[i][j]>='A')&&(c[i][j]<='Z'))
capital++;
else if((c[i][j]>='a')&&(c[i][j]<='z'))
lowercase++;
else other++;
}
}
printf("大写:%d\n小写:%d\n数字:%d\n空格:%d\n其他:%d\n",capital,lowercase,digit,space,other);
return 0;
}