C语言统计字符串中数字字符出现的次数
以下是使用C语言编写的解决方案:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int countDigits(char str[]) {
int count = 0;
int n = strlen(str);
for (int i = 0; i < n; i++) {
if (isdigit(str[i])) {
count++;
}
}
return count;
}
int main() {
int n;
scanf('%d', &n);
for (int i = 0; i < n; i++) {
char str[100];
scanf('%s', str);
int count = countDigits(str);
printf('%d\n', count);
}
return 0;
}
解释:
- 首先,定义一个函数
countDigits,用于统计字符串中数字字符的个数。函数的参数为一个字符数组str。 - 在函数中,定义一个变量
count用于计数。 - 使用一个循环,遍历字符串中的每个字符。
- 使用
isdigit函数判断字符是否为数字字符,如果是,则计数器加一。 - 返回计数器的值,即数字字符的个数。
- 在
main函数中,首先读取输入的测试实例个数n。 - 使用一个外层循环,重复处理n行测试数据。
- 在每一行测试数据中,使用
scanf函数读取一个由字母和数字组成的字符串。 - 调用
countDigits函数统计数字字符的个数,并输出结果。 - 注意:在示例代码中,我们假设输入的字符串长度不超过100。您可以根据实际情况进行调整。
原文地址: https://www.cveoy.top/t/topic/dhRq 著作权归作者所有。请勿转载和采集!