用c语言写一个输入一串字符,按Enter键结束输入,分别输出其中的英文字母、数字字符和其他字符的个数
时间: 2023-05-21 08:03:47 浏览: 93
好的,以下是用C语言实现输入一串字符,按Enter键结束输入,分别输出其中的英文字母、数字字符和其他字符的个数的代码:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int i, alpha = 0, digit = 0, other = 0;
printf("请输入一串字符,按Enter键结束输入:\n");
fgets(str, 100, stdin);
for (i = 0; str[i] != '\0'; i++) {
if (isalpha(str[i])) {
alpha++;
} else if (isdigit(str[i])) {
digit++;
} else {
other++;
}
}
printf("其中英文字母的个数为:%d\n", alpha);
printf("其中数字字符的个数为:%d\n", digit);
printf("其中其他字符的个数为:%d\n", other);
return 0;
}
```
希望这个代码能够帮到你!
相关问题
从键盘输入一串字符(按回车键结束),统计其中英文字母、数字字符、空格和其它字符的个数。
这段代码是一个C语言程序,它的功能是从键盘输入一串字符并统计其中英文字母、数字字符、空格和其他字符的个数。具体实现方法如下:
1. 定义变量letter、num、blank、tab、enter、other分别表示英文字母、数字字符、空格、Tab键、回车键和其他字符的个数。
2. 使用while循环读取输入的字符,直到读取到回车键为止。
3. 在循环中,使用if语句判断读取到的字符是英文字母、数字字符、空格、Tab键、回车键还是其他字符,并分别对应地增加相应的计数器。
4. 最后输出各个计数器的值即可。
用c语言实现,输入一个字符串,分别统计出其中英文字母、数字和其他字符的个数
```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;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)