c语言输入一行字符,分别统计出其中英文字母、空格、数字和其他字符的个数。
时间: 2023-05-24 08:06:47 浏览: 71
```c
#include <stdio.h>
#include <ctype.h>
int main()
{
char str[100];
int letters = 0, digits = 0, spaces = 0, others = 0;
printf("Please enter a string: ");
fgets(str, sizeof(str), stdin);
for (int i = 0; str[i] != '\0'; i++)
{
if (isalpha(str[i]))
letters++;
else if (isdigit(str[i]))
digits++;
else if (isspace(str[i]))
spaces++;
else
others++;
}
printf("Letters: %d\n", letters);
printf("Digits: %d\n", digits);
printf("Spaces: %d\n", spaces);
printf("Others: %d\n", others);
return 0;
}
```
说明:
1. 定义一个`char`类型数组`str`存储输入的字符串,数组长度为100。
2. 定义计数器变量`letters`, `digits`, `spaces`, `others`分别为英文字母、数字、空格和其他字符的计数器,初始值都为0。
3. 使用`fgets()`函数输入一行字符,输入的字符串包括回车符,因此需要在字符串长度判断时使用`\0`作为结束标志。
4. 使用for循环遍历字符串的每一个字符,对于每一个字符,使用`isalpha()`函数判断是否为字母,使用`isdigit()`函数判断是否为数字,使用`isspace()`函数判断是否为空格,如果都不是则为其他字符。
5. 根据字符类型,相应的计数器加1。
6. 最后输出各个计数器的值。
相关推荐
![](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)
![](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)