用c语言实现,输入一个字符串,分别统计出其中英文字母、数字和其他字符的个数
时间: 2023-05-30 18:04:32 浏览: 111
```c
#include <stdio.h>
int main()
{
char str[100];
int alphabets = 0, digits = 0, others = 0;
printf("Enter a string: ");
gets(str);
for(int i=0; str[i]!='\0'; i++)
{
if((str[i]>='a' && str[i]<='z') || (str[i]>='A' && str[i]<='Z'))
alphabets++;
else if(str[i]>='0' && str[i]<='9')
digits++;
else
others++;
}
printf("Number of alphabets: %d\n", alphabets);
printf("Number of digits: %d\n", digits);
printf("Number of other characters: %d\n", others);
return 0;
}
```
注意:上述代码使用了 gets 函数来获取输入的字符串,但 gets 函数存在安全问题,因此应该使用 fgets 函数来代替,如下所示:
```c
#include <stdio.h>
#include <string.h>
int main()
{
char str[100];
int alphabets = 0, digits = 0, others = 0;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
str[strcspn(str, "\n")] = '\0'; // 将输入的换行符替换为字符串结束符
for(int i=0; str[i]!='\0'; i++)
{
if((str[i]>='a' && str[i]<='z') || (str[i]>='A' && str[i]<='Z'))
alphabets++;
else if(str[i]>='0' && str[i]<='9')
digits++;
else
others++;
}
printf("Number of alphabets: %d\n", alphabets);
printf("Number of digits: %d\n", digits);
printf("Number of other characters: %d\n", others);
return 0;
}
```
阅读全文