用C语言2.编写程序,用户从键盘输入一字符串,字符串中含有空格,程序统计第一个空格前字符的个数。
时间: 2024-02-22 15:59:43 浏览: 26
以下是 C 语言的实现代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char s[100];
printf("请输入一个字符串:");
fgets(s, sizeof(s), stdin); // 从键盘读入字符串
int index = strchr(s, ' ') - s; // 查找第一个空格的位置
int count;
if (index == strlen(s) || index == -1) { // 如果找不到空格
count = strlen(s) - 1; // 字符个数为整个字符串长度减去末尾的换行符
} else {
count = index; // 字符个数为第一个空格前的位置
}
printf("第一个空格前的字符个数为:%d\n", count);
return 0;
}
```
运行程序后,会提示用户输入一个字符串。程序使用 `fgets` 函数从键盘读入字符串,再使用 `strchr` 函数查找第一个空格的位置,如果找不到空格,则整个字符串都是第一个空格前的字符,字符个数为字符串长度减去末尾的换行符;否则,字符个数为第一个空格前的位置。最后,程序输出结果。
相关问题
编写C语言程序,从键盘上任意输入一字符串,统计输出该字符串中的字母字符、数字字符、空格以及其他字符的个数
可以使用一个字符数组来存储用户输入的字符串,然后遍历数组中的每个字符,统计字母字符、数字字符、空格以及其他字符的个数。下面是一个示例程序:
```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, 100, 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("The string contains:\n");
printf("%d letters\n", letters);
printf("%d digits\n", digits);
printf("%d spaces\n", spaces);
printf("%d other characters\n", others);
return 0;
}
```
用户输入一个字符串后,程序会统计其中字母字符、数字字符、空格以及其他字符的个数,并输出结果。注意,我们使用了 `<ctype.h>` 库中的 `isalpha()`、`isdigit()` 和 `isspace()` 函数来判断字符的类型。
编写C语言程序,从键盘上任意输入一字符串,统计输出该字符串中的字母字符、数字字符、空格数减一以及其他字符的个数
可以使用一个字符数组来存储用户输入的字符串,然后遍历数组中的每个字符,统计字母字符、数字字符、空格以及其他字符的个数,并计算空格数减一的个数。下面是一个示例程序:
```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, 100, 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("The string contains:\n");
printf("%d letters\n", letters);
printf("%d digits\n", digits);
printf("%d spaces\n", spaces - 1);
printf("%d other characters\n", others);
return 0;
}
```
用户输入一个字符串后,程序会统计其中字母字符、数字字符、空格以及其他字符的个数,并计算空格数减一的个数,并输出结果。注意,我们使用了 `<ctype.h>` 库中的 `isalpha()`、`isdigit()` 和 `isspace()` 函数来判断字符的类型。