用C语言统计一个字符串中数字字符的个数。
时间: 2024-03-24 14:14:49 浏览: 16
好的,下面是用C语言统计一个字符串中数字字符的个数的代码:
```c
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main()
{
char str[100];
int len, i, count = 0;
printf("请输入一个字符串:\n");
scanf("%s", str);
len = strlen(str); // 计算字符串的长度
for (i = 0; i < len; i++)
{
if (isdigit(str[i])) // 判断是否为数字字符
{
count++; // 统计数字字符的个数
}
}
printf("字符串中数字字符的个数为:%d\n", count);
return 0;
}
```
希望能够帮助到您,有什么其他问题可以继续提问。
相关问题
c语言定义函数统计字符串中数字字符的个数
可以用以下代码实现:
```c
#include<stdio.h>
#include<string.h>
int count_num_char(const char* str) {
int count = 0;
for(int i = 0; i < strlen(str); i++) {
if(str[i] >= '0' && str[i] <= '9') {
count++;
}
}
return count;
}
int main() {
char str[] = "Hello 123 World";
int count = count_num_char(str);
printf("Number of digit characters in the string: %d\n", count);
return 0;
}
```
这个程序中,我们定义了一个 `count_num_char` 函数,它接收一个字符串作为参数,返回字符串中数字字符的个数。我们首先初始化计数器 `count` 为 0,然后遍历字符串中的每个字符。如果字符是数字字符,则将计数器加 1。最后,函数返回计数器的值。
在主函数中,我们定义了一个字符串 `str`,并调用 `count_num_char` 函数来统计其中数字字符的个数。
用c语言统计一个字符串中字母、数字、空格和其他字符的个数
```c
#include <stdio.h>
int main() {
char str[100];
int letter = 0, digit = 0, space = 0, other = 0;
printf("请输入一个字符串:");
fgets(str, 100, stdin);
for (int i = 0; str[i] != '\0'; i++) {
if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z')) {
letter++;
} else if (str[i] >= '0' && str[i] <= '9') {
digit++;
} else if (str[i] == ' ' || str[i] == '\t' || str[i] == '\n') {
space++;
} else {
other++;
}
}
printf("字母个数:%d\n", letter);
printf("数字个数:%d\n", digit);
printf("空格个数:%d\n", space);
printf("其他字符个数:%d\n", other);
return 0;
}
```
说明:
1. 定义一个字符数组 `str` 存放输入的字符串,定义四个变量 `letter`、`digit`、`space` 和 `other` 分别统计字母、数字、空格和其他字符的个数。
2. 使用 `fgets` 函数从标准输入中读取一个字符串,遇到换行符停止读取,最多读取 100 个字符。
3. 使用 `for` 循环遍历字符串中的每个字符,判断其属于哪一类字符,分别更新对应变量的值。
4. 使用 `printf` 函数输出结果。