用c语言写出统计一个字符串中的字母,数字、空格和其他字符的个数
时间: 2023-04-06 07:00:28 浏览: 82
你好,这个问题可以回答。以下是用 C 语言实现统计字符串中字母、数字、空格和其他字符个数的代码:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int letters = 0, digits = 0, spaces = 0, others = 0;
printf("请输入一个字符串:");
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("字母个数:%d\n", letters);
printf("数字个数:%d\n", digits);
printf("空格个数:%d\n", spaces);
printf("其他字符个数:%d\n", others);
return 0;
}
```
希望能对你有所帮助。
相关问题
c语言中编一函数,统计一个字符串中字母数字空格和其他字符的个数简单点
,能否给出示例代码?
当然可以!以下是一个简单的函数,可以实现统计一个字符串中字母、数字、空格和其他字符的个数:
```
#include <stdio.h>
void countChars(char *str) {
int letters = 0;
int digits = 0;
int spaces = 0;
int others = 0;
while (*str != '\0') {
if (isalpha(*str)) {
letters++;
} else if (isdigit(*str)) {
digits++;
} else if (isspace(*str)) {
spaces++;
} else {
others++;
}
str++;
}
printf("字符串中字母数量:%d\n", letters);
printf("字符串中数字数量:%d\n", digits);
printf("字符串中空格数量:%d\n", spaces);
printf("字符串中其他字符数量:%d\n", others);
}
int main() {
char str[100];
printf("请输入一个字符串:");
fgets(str, sizeof(str), stdin);
countChars(str);
return 0;
}
```
这个函数中,我们利用了`isalpha`、`isdigit`和`isspace`这几个函数来判断字符属于字母、数字还是空格。如果都不是,则认为是其他字符。
C语言中编一函数,统计一个字符串中字母数字空格和其他字符的个数
好的,这个问题可以通过编写一个函数来实现。下面是一个简单的 C 语言函数示例:
```c
#include <stdio.h>
#include <ctype.h>
void count_chars(const char *str, int *alpha, int *num, int *space, int *other) {
while (*str) {
if (isalpha(*str))
(*alpha)++;
else if (isdigit(*str))
(*num)++;
else if (*str == ' ')
(*space)++;
else
(*other)++;
str++;
}
}
int main() {
int alpha = 0, num = 0, space = 0, other = 0;
char str[] = "Hello, 123 world!";
count_chars(str, &alpha, &num, &space, &other);
printf("Alpha: %d\n", alpha);
printf("Num: %d\n", num);
printf("Space: %d\n", space);
printf("Other: %d\n", other);
return 0;
}
```
这个函数接收一个字符串和四个指针变量作为参数,分别统计字母、数字、空格和其他字符的数量,并将结果存储在指针变量中。在主函数中,我们可以传入一个测试字符串,并打印出结果。
注意:本人是 AI 语言模型,对于代码的语法分析能力很强,但对于代码的执行能力很弱。本回答提供的代码仅供参考,实际运行效果可能存在问题。
相关推荐














