求输入字符串中的英文字母,数字,空格,以及其它字符的个数常见错误
首先
用scanf()输入字符串时应注意该函数不能接收空格,即与空格键,回车键,tab键时,认为字符串已输入完,作用相当于字符串中的‘\0’,而gets()函数可以接收空格键,回车键,tab键。
scanf :当遇到回车,空格和tab键会自动在字符串后面添加’\0’,但是回车,空格和tab键仍会留在输入的缓冲区中。
gets:可接受回车键之前输入的所有字符,并用’\n’替代 ‘\0’.回车键不会留在输入缓冲区中
gets()用到读取字符串,用回车结束输入
scanf()可以读取所有类型的变量
注意:以上两个函数同属于同一个头文件stdio.h。
其次
我们在判断字符串是否完结时常用sizeof()和strlen()这两个函数。sizeof()会将字符串结束标志‘\0’计算在内, 而strlen()则不会,故两者针对同一个字符串是,其值相差1。
注意sizeof()不是函数而是运算符。
最后
举两个例子!
代码一:
*#include <stdio.h>
#include <string.h>
void count(char s[]);
int main()
{
char str[20];
gets(str);
count(str);
return 0;
}
void count(char s[])
{
int n=strlen(s);
int letter=0, num=0, space=0, other=0;
for (int i=0; i<n; i++){
if ((s[i]>='a'&&s[i]<='z')||(s[i]>='A'&&s[i]<='Z')) letter++;
else if (s[i]>='0'&&s[i]<='9') num++;
else if (s[i]==' '||s[i]=='\t') space++;
else other++;
}
printf("%d %d %d %d\n", letter, num, space, other);
}
运行输出结果为:
代码二:
#include<stdio.h>
#include<string.h>
int main(void)
{
/*********Begin*********/
char str[200];
scanf("%s",str);
int i,english=0,shu=0,kong=0,qita=0;
for(i=0;i<strlen(str);i++)
{
if((str[i]>='a'&&str[i]<='z')||(str[i]>='A'&&str[i]<='Z'))++english;
else if(str[i]>='0'&&str[i]<='9') ++shu;
else if(str[i]==' '||str[i]=='\t')++kong;
else ++qita;
}
printf("%d %d %d %d",english,shu,kong,qita);
/*********End**********/
return 0;
}
运行结果为;