找出字符串中数字字符出现的次数,用C语言写
时间: 2024-12-18 20:15:09 浏览: 29
在C语言中,你可以通过遍历字符串并逐个检查每个字符是否为数字字符来计算字符串中数字字符出现的次数。下面是一个简单的示例函数,它接受一个字符串作为输入,并返回数字字符的数量:
```c
#include <stdio.h>
#include <ctype.h>
int count_digits(char* str) {
int count = 0;
while (*str != '\0') { // 遍历直到字符串结束
if (isdigit(*str)) { // 检查当前字符是否是数字
count++;
}
str++; // 移动到下一个字符
}
return count; // 返回计数值
}
// 示例用法
int main() {
char str[] = "abc123def456";
int digit_count = count_digits(str);
printf("数字字符在字符串中共出现了 %d 次。\n", digit_count);
return 0;
}
```
在这个例子中,`isdigit()` 函数用于检查字符是否为数字。如果字符是数字,计数器 `count` 就会递增。当遍历完整个字符串后,`count_digits` 函数将返回数字字符的总数。
阅读全文
相关推荐


















