用c语言编写一程序,分别计算所输入的字符串中空格,换行符的个数,字符串以字符z做为结束符号。
时间: 2024-02-06 20:10:39 浏览: 25
以下是一个简单的C语言程序,可以实现输入字符串并计算其中空格和换行符的个数,直到遇到字符 'z' 为止:
```c
#include <stdio.h>
int main() {
char c;
int space_count = 0, newline_count = 0;
printf("请输入字符串(以字符 'z' 结束):\n");
while ((c = getchar()) != 'z') {
if (c == ' ') {
space_count++;
} else if (c == '\n') {
newline_count++;
}
}
printf("空格数:%d\n", space_count);
printf("换行数:%d\n", newline_count);
return 0;
}
```
该程序中使用了一个 while 循环来读取输入的字符,直到读取到字符 'z' 为止。在循环体中,使用了 if 来判断读取到的字符是否为空格或换行符,并分别增加对应的计数器。
最后输出计数器的值即可。
相关问题
C语言 编写一程序,分别计算所输入的字符串中空格,换行符的个数。
Sure! 下面是一个示例程序,可以计算输入字符串中空格和换行符的个数:
```c
#include <stdio.h>
int main() {
char str[100];
int spaceCount = 0;
int newlineCount = 0;
printf("请输入字符串:");
fgets(str, sizeof(str), stdin);
for (int i = 0; str[i] != '\0'; i++) {
if (str[i] == ' ') {
spaceCount++;
}
if (str[i] == '\n') {
newlineCount++;
}
}
printf("空格的个数:%d\n", spaceCount);
printf("换行符的个数:%d\n", newlineCount);
return 0;
}
```
你可以通过运行该程序并输入一个字符串来测试它。它会输出字符串中空格和换行符的个数。
C语言编写程序输入一个以回车符结束的字符串,分别统计其中英文字母、数字、其他字符的个数
好的,这是一个比较基础的 C 语言编程问题。下面是一个简单的程序,可以实现输入一个以回车符结束的字符串,然后统计其中英文字母、数字、其他字符的个数:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int letter_count = 0, digit_count = 0, other_count = 0;
printf("请输入一个字符串:");
fgets(str, 100, stdin); // 读入一个以回车符结束的字符串
for (int i = 0; str[i] != '\0'; i++) {
if (isalpha(str[i])) { // 如果是英文字母
letter_count++;
} else if (isdigit(str[i])) { // 如果是数字
digit_count++;
} else { // 其他字符
other_count++;
}
}
printf("其中英文字母个数为:%d,数字个数为:%d,其他字符个数为:%d\n", letter_count, digit_count, other_count);
return 0;
}
```
在这个程序中,我们首先定义了一个字符数组 `str`,用于存储输入的字符串。然后定义了三个变量 `letter_count`、`digit_count`、`other_count`,分别用于统计英文字母、数字、其他字符的个数,初始值都为 0。
接下来使用 `fgets` 函数读入一个以回车符结束的字符串,最多读入 99 个字符(因为还要留一个位置存储字符串末尾的空字符)。
然后使用一个 for 循环遍历字符串中的每个字符,使用 `isalpha` 和 `isdigit` 函数判断该字符是不是英文字母或数字,从而分别累加统计变量的值。如果既不是英文字母也不是数字,则认为是其他字符,也进行累加。
最后输出三个统计变量的值即可。