C语言统计字符串中所有数字字符的数值和
时间: 2024-03-10 17:44:31 浏览: 18
好的,以下是一个用 C 语言实现统计字符串中所有数字字符的数值和的程序:
```c
#include <stdio.h>
#include <ctype.h>
int sum_all_digits_in_string(char* s) {
int total = 0;
while (*s) {
if (isdigit(*s)) {
total += *s - '0';
}
s++;
}
return total;
}
int main() {
char str[] = "hello 123 world 456";
int total = sum_all_digits_in_string(str);
printf("%d\n", total); // 输出 21
return 0;
}
```
该程序与前面的程序类似,不同之处在于它统计了字符串中所有数字字符的数值和,而不仅仅是整数字符。同样地,我们也是使用了 `isdigit()` 函数来判断当前字符是否为数字字符,如果是,则将其转换为整数并加到数值和中。
使用示例中,我们首先定义了一个字符串 `str`,然后调用 `sum_all_digits_in_string()` 函数,将字符串作为参数传递给它,计算出字符串中所有数字字符的数值和,并输出结果。
同样需要注意的是,上述代码中的 `isdigit()` 函数需要包含头文件 `ctype.h`,因此在程序开头我们需要使用 `#include` 指令来引入该头文件。