用C语言编写一个函数,统一字符串中字母、数字、空格和其他字符的个数
时间: 2024-06-13 12:06:56 浏览: 20
以下是用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);
return 0;
}
```
相关问题
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 语言模型,对于代码的语法分析能力很强,但对于代码的执行能力很弱。本回答提供的代码仅供参考,实际运行效果可能存在问题。
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`这几个函数来判断字符属于字母、数字还是空格。如果都不是,则认为是其他字符。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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_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)