编写测试程序,输⼊⼀个字符串,显示字符串中的字⺟个数
若函数countLetters()⽤于统计字符串中英⽂字⺟的个数(不区分⼤⼩
写),并且它的函数声明如下:
• int countLetters(char s[]);
• 测试⽤例
• 输⼊:123Cc@!X
• 输出:3
#include<stdio.h>
int countLetters(char s[]){
int i, count = 0;
for(i = 0; s[i] != '\0'; i++){
if('a' <= s[i] && s[i] <= 'z' || 'A' <= s[i] && s[i] <= 'Z'){
count++;
}
}
return count;
}
int main(){
char s[1000];
scanf("%s", s);
printf("%d", countLetters(s));
return 0;
}
供参考:
int countLetters(char s[])
{
int cnt = 0;
char* p = s;
while (*p) {
if ((*p >= 'a' && *p <= 'z') || (*p >= 'A' && *p <= 'Z')) cnt++;
p++;
}
return cnt;
}
有很多方法,可以用循环,对ascii码值进行判断,来判断他是不是字符,也可以用ctype.h中的库函数isalpha来判断