使用C语言查找字符串中的字母,数字和特殊字符的数量
以下是我们用于查找字母,数字和特殊字符的逻辑-
for(number=0;string[number]!='\0';number++) //for循环,直到字符串结尾{ if(string[number]>='a'&&string[number]<='z'||string[number]>='A'&&string[number]<='Z') //检查字符串中的字母{ alphabets=alphabets+1; //数字母 //alphabets++; }else if(string[number]>='0'&&string[number]<='9') //检查字符串中的数字{ digits=digits+1; //数数 //digits++; }else{ special=special+1; //计数特殊字符 //special++; } }
接下来的程序是识别字符串中的字母,数字和特殊字符的总数-
示例
#include<stdio.h> #include<ctype.h> void main(){ //Declaring integer for number determination, string// int number; char string[50]; int alphabets=0; int digits=0; int special=0; //Reading User I/p// printf("输入字符串:"); gets(string); for(number=0;string[number]!='\0';number++){ if(string[number]>='a'&&string[number]<='z'||string[number]>='A'&&string[number]<='Z'){ alphabets=alphabets+1; //alphabets++; }else if(string[number]>='0'&&string[number]<='9'){ digits=digits+1; //digits++; }else{ special=special+1; //special++; } } //Printing number of alphabets, number of digits, number of special characters// printf("The number of alphabets in the string is : %d\n",alphabets); printf("The number of digits in the string is : %d\n",digits); printf("The number of special characters in the string is : %d\n",special); }输出结果
输入字符串:The number of alphabets in the string is : 0 The number of digits in the string is : 0 The number of special characters in the string is : 1