C语言编写函数,求给定字符串中数字字符的个数,在主函数中输入字符串及输出统计的个数。
时间: 2023-06-20 21:06:16 浏览: 740
可以使用循环遍历字符串的每一个字符,判断该字符是否为数字字符,如果是,则计数器加1,最后输出计数器的值即可。
以下是示例代码:
```c
#include <stdio.h>
#include <ctype.h>
int count_digits(char *str) {
int count = 0;
while (*str) {
if (isdigit(*str)) {
count++;
}
str++;
}
return count;
}
int main() {
char str[100];
printf("请输入字符串:");
fgets(str, 100, stdin);
int count = count_digits(str);
printf("数字字符的个数为:%d\n", count);
return 0;
}
```
在上面的代码中,`count_digits` 函数用来统计数字字符的个数,它使用了一个 while 循环来遍历字符串中的每一个字符,如果当前字符是数字字符,则计数器加1。`isdigit` 函数用来判断一个字符是否为数字字符。
在主函数中,先输入字符串,然后调用 `count_digits` 函数统计数字字符的个数,并输出结果。注意,使用 `fgets` 函数来输入字符串,可以避免输入的字符串长度超过数组长度的问题。
相关问题
编写c语言函数,求给定字符串中数字字符的个数,在主函数中输入字符串及输出统计的个数
下面是一个简单的 C 语言函数,可用于计算给定字符串中数字字符的个数:
```c
#include <stdio.h>
#include <ctype.h>
int countDigits(char *str) {
int count = 0;
while (*str != '\0') {
if (isdigit(*str)) {
count++;
}
str++;
}
return count;
}
int main() {
char str[100];
printf("请输入一个字符串:");
gets(str);
int count = countDigits(str);
printf("字符串中数字字符的个数为 %d\n", count);
return 0;
}
```
该程序首先定义了一个 `countDigits` 函数,该函数使用一个指针遍历字符串,如果指针指向的字符是数字字符,则将计数器加一。最后返回计数器的值。
在主函数中,程序首先提示用户输入一个字符串,然后调用 `countDigits` 函数计算数字字符的个数,并输出结果。
用C语言编写函数,求给定字符串中数字字符的个数,在主函数中输入字符串及输出统计的个数。
以下用C语言编写函数,求给定字符串中数字字符的个数的示例代码:
```c
#include <stdio.h>
#include <string.h>
int countDigits(char str[]) {
int count = 0;
int len = strlen(str);
for (int i = 0; i < len; i++) {
if (str[i] >= '0' && str[i] <= '9') {
count++;
}
}
return count;
}
int main() {
char str[100];
printf("请输入字符串:");
scanf("%s", str);
int count = countDigits(str);
printf("数字字符的个数为:%d\n", count);
return 0;
}
```
该程序中,countDigits函数用于统计给定字符串中数字字符的个数。它接受一个字符串参数str,并返回一个整数结果count。
函数中使用了一个for循环来遍历整个字符串,对于每个字符,如果它是一个数字字符(即ASCII码值在'0'~'9'之间),则将计数器count加1。
在主函数中,首先提示用户输入字符串,然后调用countDigits函数来统计数字字符的个数,并将结果输出。