编写函数,求给定字符串中数字字符的个数,在主函数中输入字符串及输出统计的个数。c语言
时间: 2024-05-02 16:20:46 浏览: 12
以下是 C 语言的实现:
```c
#include <stdio.h>
int countNumbers(char *str) {
int count = 0;
for (int i = 0; str[i] != '\0'; i++) {
if (str[i] >= '0' && str[i] <= '9') {
count++;
}
}
return count;
}
int main() {
char str[100];
printf("请输入字符串:");
scanf("%s", str);
int count = countNumbers(str);
printf("字符串中数字字符的个数为:%d\n", count);
return 0;
}
```
以上代码中,`countNumbers` 函数统计给定字符串中数字字符的个数,`main` 函数则获取用户输入的字符串并输出统计的结果。如果字符串中的字符是数字字符,即 ASCII 码为 `'0'` 到 `'9'` 之间,则计数器加 1。
相关问题
编写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函数来统计数字字符的个数,并将结果输出。