C语言没有字符串形式,所以可以用 char[] 数组来代替,但需要指定分配空间,所以可以采用单字符读取的形式:
#include int main(){char ch;int space=0,number=0,character=0,other=0;ch=getchar(); //字符输入 while(ch!='\n'){ // '\n'是回车 if(ch==' '){ //字符ch为空' ' space++;}else if(ch>='0'&&ch<='9'){ //字符为数字0~9 number++;}else if(ch>='a'&&ch<='z'||ch>='A'&&ch<='Z'){ //字符为字母a~z,A~Z character++; }else{other++;}ch=getchar();}printf("%d %d %d %d",character,number,space,other);return 0;
}
#include
int main(){char c;int letters=0,space=0,digit=0,other=0;printf("请输入一行字符:\n");while((c=getchar())!='\n'){if(c>='a'&&c<='z'||c>='A'&&c<='Z')letters++;else if(c==' ')space++;else if(c>='0'&&c<='9')digit++;elseother++;}printf("字母数:%d\n数字数:%d\n空格数:%d\n其他字符数:%d",letters,digit,space,other);return 0;
}
嫌利用ASCII码比较太麻烦?可以试试下面
利用库函数 #include
#include
#include
int main()
{int letter=0,shuzi=0,kongge=0,qita=0,c;while((c=getchar())!='\n'){if(isalpha(c)){letter++;}else if(isdigit(c)){shuzi++;}else if(c==' '){kongge++;}else{qita++;}}printf("%d %d %d %d",letter,shuzi,kongge,qita);return 0;
}