统计字符串中符合要求的字符个数c语言
时间: 2024-06-14 15:05:03 浏览: 16
在C语言中,可以通过遍历字符串的每个字符,并使用条件语句来判断字符是否符合要求,从而统计符合要求的字符个数。以下是一个示例代码:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[1000];
int letters = 0, spaces = 0, digits = 0, others = 0;
int i = 0;
printf("请输入一个字符串:");
gets(str);
while (str[i] != '\0') {
if (isalpha(str[i])) {
letters++;
} else if (isspace(str[i])) {
spaces++;
} else if (isdigit(str[i])) {
digits++;
} else {
others++;
}
i++;
}
printf("英文字母个数:%d\n", letters);
printf("空格或回车个数:%d\n", spaces);
printf("数字个数:%d\n", digits);
printf("其他字符个数:%d\n", others);
return 0;
}
```
这段代码首先定义了一个字符数组`str`用于存储输入的字符串,然后定义了四个变量`letters`、`spaces`、`digits`和`others`分别用于统计英文字母、空格或回车、数字和其他字符的个数。接下来使用`gets()`函数获取用户输入的字符串。
然后,通过一个`while`循环遍历字符串的每个字符,使用`isalpha()`函数判断字符是否为英文字母,使用`isspace()`函数判断字符是否为空格或回车,使用`isdigit()`函数判断字符是否为数字,如果都不满足,则认为是其他字符。
最后,输出统计结果。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)