用c语言编写:输入一串字符,判断数字,字母,其他字符的个数的程序
时间: 2023-03-08 17:58:52 浏览: 104
答:#include <stdio.h>
int main()
{
char str[100];
int digits, alphabets, others;
digits = alphabets = others = 0;
printf("请输入一串字符:");
gets(str);
for(int i=0; str[i]!='\0'; i++)
{
if(str[i]>='0' && str[i]<='9')
digits++;
else if((str[i]>='A' && str[i]<='Z') || (str[i]>='a' && str[i]<='z'))
alphabets++;
else
others++;
}
printf("字母个数: %d\n", alphabets);
printf("数字个数: %d\n", digits);
printf("其他字符个数: %d\n", others);
return 0;
}
相关问题
c语言编写:输入一个长度小于80的字符串,统计其中字母的个数
好的,以下是使用C语言编写的程序,实现统计输入字符串中字母的个数:
```c
#include <stdio.h>
#include <string.h>
int main()
{
char str[80];
int i, count = 0;
printf("请输入一个字符串(长度小于80):");
fgets(str, 80, stdin);
for (i = 0; i < strlen(str); i++) {
if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z')) {
count++;
}
}
printf("该字符串中字母的个数为:%d\n", count);
return 0;
}
```
程序首先使用`fgets()`函数从标准输入中读取一个字符串,存储在字符数组`str`中。接着,使用一个循环遍历字符串中的每一个字符,如果该字符是字母(即ASCII码在65~90或97~122之间),就将计数器加1。最后输出字母的个数。
需要注意的是,使用`fgets()`函数可以避免输入字符串长度超过80个字符的问题,而使用`gets()`函数可能会导致缓冲区溢出。此外,为了判断一个字符是否是字母,程序使用了ASCII码值的比较。
用c语言编写:输入一行字符,分别统计出其中英文字母、空格、数字和其他字符的个数。
好的,这个问题是计算类问题,可以回答。以下是C语言的代码:
#include <stdio.h>
int main()
{
char str[100];
int letters = 0, spaces = 0, digits = 0, others = 0;
printf("请输入一行字符:");
gets(str);
for(int i = 0; str[i] != '\0'; i++)
{
if(str[i] >= 'a' && str[i] <= 'z' || str[i] >= 'A' && str[i] <= 'Z')
{
letters++;
}
else if(str[i] == ' ')
{
spaces++;
}
else if(str[i] >= '0' && str[i] <= '9')
{
digits++;
}
else
{
others++;
}
}
printf("字母个数:%d\n", letters);
printf("空格个数:%d\n", spaces);
printf("数字个数:%d\n", digits);
printf("其他字符个数:%d\n", others);
return 0;
}