用C语言编写函数,统计字符串中数字字符的个数
时间: 2024-05-01 19:18:47 浏览: 392
好的,这个问题很简单。以下是一个用C语言编写的函数,可以统计字符串中数字字符的个数:
```
int countDigits(char* str) {
int count = 0;
for (int i = 0; str[i] != '\0'; i++) {
if (isdigit(str[i])) {
count++;
}
}
return count;
}
```
你可以调用这个函数并传入一个字符串,它将返回该字符串中数字字符的个数。希望这能帮到你!
相关问题
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 count_digits(char *str) {
int count = 0;
while (*str) {
if (*str >= '0' && *str <= '9') {
count++;
}
str++;
}
return count;
}
int main() {
char str[100];
printf("请输入一串字符:");
scanf("%s", str);
printf("数字字符的个数是:%d\n", count_digits(str));
return 0;
}
```
解释:
首先,在主函数中定义一个字符串数组 `str`,用于存放输入的字符串。然后,调用 `scanf` 函数从标准输入中读取字符串并将其存入 `str` 中。
接下来,调用 `count_digits` 函数,将输入的字符串作为参数传入,统计其中数字字符的个数并返回结果。
`count_digits` 函数中,定义一个整数变量 `count`,用于记录数字字符的个数。然后使用一个 `while` 循环遍历字符串,对于每个字符,判断它是否为数字字符。如果是,则将 `count` 的值加 1。最后,返回 `count` 的值作为结果。
阅读全文
相关推荐














