用C语言编写一个程序:键盘输入一个字符串,统计其中数字、英文字符、空格和其它字符的个数。
时间: 2024-05-08 08:19:02 浏览: 12
我可以回答这个问题。下面是用C语言编写的示例代码:
```c
#include <stdio.h>
int main() {
char str[100];
int i, digits = 0, letters = 0, spaces = 0, others = 0;
printf("请输入一串字符串:");
gets(str);
for (i = 0; str[i] != '\0'; i++) {
if (str[i] >= '0' && str[i] <= '9') {
digits++;
} else if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z')) {
letters++;
} else if (str[i] == ' ') {
spaces++;
} else {
others++;
}
}
printf("字符串中有 %d 个数字,%d 个英文字符,%d 个空格,%d 个其他字符。\n", digits, letters, spaces, others);
return 0;
}
```
它会读取一个字符串,并统计其中数字、英文字符、空格和其他字符的个数。
相关问题
用C语言编写一个函数,统计一个输入字符串中字母、数字、空格和其它字符的个数。
下面是用C语言编写的一个函数,可以统计输入字符串中字母、数字、空格和其它字符的个数:
```c
#include <stdio.h>
#include <ctype.h>
void count_chars(const char* str, int* num_letters, int* num_digits, int* num_spaces, int* num_others) {
*num_letters = *num_digits = *num_spaces = *num_others = 0;
while (*str != '\0') {
if (isalpha(*str)) {
(*num_letters)++;
} else if (isdigit(*str)) {
(*num_digits)++;
} else if (isspace(*str)) {
(*num_spaces)++;
} else {
(*num_others)++;
}
str++;
}
}
int main() {
char str[100];
int num_letters, num_digits, num_spaces, num_others;
printf("请输入字符串:\n");
fgets(str, sizeof(str), stdin);
count_chars(str, &num_letters, &num_digits, &num_spaces, &num_others);
printf("字母个数:%d\n", num_letters);
printf("数字个数:%d\n", num_digits);
printf("空格个数:%d\n", num_spaces);
printf("其它字符个数:%d\n", num_others);
return 0;
}
```
在上面的代码中,我们定义了一个`count_chars`函数,接受一个字符串指针和四个整型指针作为参数,分别用于记录字母、数字、空格和其它字符的个数。在函数内部,我们使用`while`循环遍历字符串中的每一个字符,判断其是否为字母、数字、空格或其它字符,并根据结果更新相应的计数器。最后,在`main`函数中,我们通过调用`count_chars`函数并传递相应的参数来统计字符串中的各种字符的个数,并将结果输出到屏幕上。
C语言写程序:输入一行字符,分别统计其中的英文字母、空格、数字和其他字符的个数
这是一段C语言程序,它的功能是输入一行字符,然后统计其中的英文字母、空格、数字和其他字符的个数。程序使用了gets函数来获取用户输入的字符串,然后使用for循环遍历字符串中的每个字符,根据字符的类型进行统计。最后输出统计结果。
以下是回答:
这段C语言程序的功能是输入一行字符,然后统计其中的英文字母、空格、数字和其他字符的个数。程序使用了gets函数来获取用户输入的字符串,然后使用for循环遍历字符串中的每个字符,根据字符的类型进行统计。最后输出统计结果。
具体来说,程序使用了四个变量来分别统计英文字母、数字、空格和其他字符的个数。在for循环中,使用了if语句来判断当前字符的类型,并根据类型对相应的变量进行加一操作。最后,使用printf函数输出统计结果。