用c语言编写输入一个字符串,统计数字字符的个数
时间: 2024-05-13 22:14:12 浏览: 13
下面是一个简单的 C 语言程序,用于输入一个字符串并统计其中的数字字符个数:
```c
#include <stdio.h>
#include <ctype.h>
int main()
{
char str[100];
int i, count = 0;
printf("请输入一个字符串:");
scanf("%s", str);
for (i = 0; str[i] != '\0'; i++) {
if (isdigit(str[i])) {
count++;
}
}
printf("数字字符的个数为:%d\n", count);
return 0;
}
```
该程序首先使用 `scanf()` 函数获取用户输入的字符串,然后使用 `isdigit()` 函数判断每个字符是否为数字字符(即 `'0'` 到 `'9'` 之间的字符),最后通过一个计数器变量统计数字字符的个数并输出结果。
相关问题
c语言编写程序输入一个字符串,统计字符串中字符的个数
可以使用C语言的字符串库函数`strlen()`来统计字符串中字符的个数。以下是一个示例程序:
```c
#include <stdio.h>
#include <string.h>
int main()
{
char str[100];
int len;
printf("请输入一个字符串:");
scanf("%s", str);
len = strlen(str);
printf("该字符串中字符的个数为:%d\n", len);
return 0;
}
```
在程序中,先定义一个字符数组`str`,用于存储输入的字符串。然后使用`scanf()`函数获取用户输入的字符串。接着调用`strlen()`函数获取字符串中字符的个数,并将结果赋给变量`len`。最后,使用`printf()`函数输出结果。
用C语言编写函数,统计字符串中数字字符的个数
好的,这个问题很简单。以下是一个用C语言编写的函数,可以统计字符串中数字字符的个数:
```
int countDigits(char* str) {
int count = 0;
for (int i = 0; str[i] != '\0'; i++) {
if (isdigit(str[i])) {
count++;
}
}
return count;
}
```
你可以调用这个函数并传入一个字符串,它将返回该字符串中数字字符的个数。希望这能帮到你!