c语言统计字符串中空格数
时间: 2023-12-12 21:02:19 浏览: 78
可以使用循环遍历字符串中的每一个字符,判断是否为空格,如果是,则计数器加一。代码如下:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
int count = 0;
printf("请输入一个字符串:");
fgets(str, sizeof(str), stdin); // 从标准输入读取字符串
for (int i = 0; i < strlen(str); i++) {
if (str[i] == ' ') { // 如果当前字符是空格
count++; // 计数器加一
}
}
printf("空格数为:%d\n", count);
return 0;
}
```
注意:这里使用了 `fgets()` 函数来从标准输入读取字符串,因为 `gets()` 函数存在安全隐患,不建议使用。
相关问题
C语言统计字符串中字母 数字 空格 其他字符个数
以下是C语言统计字符串中字母、数字、空格、其他字符个数的代码实现:
```c
#include <stdio.h>
#include <ctype.h>
void count(char str[]) {
int i, letter = 0, digit = 0, space = 0, other = 0;
for (i = 0; str[i] != '\0'; i++) {
if (isalpha(str[i])) { // 判断是否为字母
letter++;
} else if (isdigit(str[i])) { // 判断是否为数字
digit++;
} else if (isspace(str[i])) { // 判断是否为空格
space++;
} else { // 其他字符
other++;
}
}
printf("字母个数:%d\n", letter);
printf("数字个数:%d\n", digit);
printf("空格个数:%d\n", space);
printf("其他字符个数:%d\n", other);
}
int main() {
char str[100];
printf("请输入字符串:");
gets(str); // 读入字符串
count(str); // 调用count函数统计字符个数
return 0;
}
```
c语言统计字符串中单词个数
可以使用以下方法来统计字符串中单词的个数:
1. 遍历字符串中的每一个字符
2. 如果当前字符不是空格、制表符或换行符,则标记为一个单词的起始位置
3. 如果当前字符是空格、制表符或换行符,则标记为一个单词的结束位置
4. 如果当前字符是字符串的结束符,则标记为一个单词的结束位置
5. 如果当前位置是单词的结束位置,则单词计数器加1
6. 重复步骤1-5直到遍历完整个字符串
下面是一个示例代码:
```c
#include <stdio.h>
#include <string.h>
int countWords(char *str) {
int count = 0;
int isWord = 0; // 标记当前位置是否为一个单词的起始位置
while (*str) {
if (*str != ' ' && *str != '\t' && *str != '\n') {
if (!isWord) { // 如果当前位置不是一个单词的起始位置,则标记为起始位置
isWord = 1;
count++;
}
} else {
isWord = 0; // 如果当前位置是空格、制表符或换行符,标记为单词的结束位置
}
str++;
}
return count;
}
int main() {
char str[100];
printf("请输入字符串:");
fgets(str, sizeof(str), stdin);
str[strlen(str) - 1] = '\0'; // 去掉fgets读入的换行符
int count = countWords(str);
printf("单词个数为:%d\n", count);
return 0;
}
```
这个程序通过遍历字符串中的每个字符来统计单词个数,同时使用一个标记变量isWord来判断当前位置是否为一个单词的起始位置。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)