用c语言的gets函数求一个长度不超过30的字符串中数字的个数
时间: 2023-06-01 11:05:16 浏览: 61
你好,这是一个编程问题,可以回答。以下是使用 gets 函数求一个长度不超过30的字符串中数字的个数的示例代码:
```
#include <stdio.h>
#include <ctype.h>
int main() {
char str[31]; // 声明字符串变量
int count = 0; // 记录数字个数的变量
printf("请输入字符串:");
gets(str);
for (int i = 0; str[i] != '\0'; i++) { // 遍历字符串中的每个字符
if (isdigit(str[i])) { // 如果字符是数字
count++; // 数字个数加1
}
}
printf("数字个数为:%d\n", count);
return 0;
}
```
相关问题
用C语言编写程序,统计字符串中数字字符的个数。(使用gets函数接收字符串)
好的,下面是代码示例:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
int count = 0, len;
printf("请输入字符串:");
gets(str);
len = strlen(str);
for (int i = 0; i < len; i++) {
if (str[i] >= '0' && str[i] <= '9') {
count++;
}
}
printf("字符串中数字字符的个数为:%d\n", count);
return 0;
}
```
这段代码中,我们首先定义了一个字符串数组 `str`,用于存储输入的字符串。然后使用 `gets` 函数接收用户输入的字符串。接着,使用 `strlen` 函数获取字符串的长度,用于循环统计数字字符的个数。在循环中,使用 `if` 判断当前字符是否为数字字符,若是则计数器 `count` 加一。最后输出计数器的值即可。
用C语言编写一个函数,统一字符串中字母、数字、空格和其他字符的个数
以下是用C语言编写一个函数,统计字符串中字母、数字、空格和其他字符的个数的例子:
```c
#include <stdio.h>
#include <ctype.h>
void count(char str[]) {
int i, letter = 0, digit = 0, space = 0, other = 0;
for (i = 0; str[i] != '\0'; i++) {
if (isalpha(str[i])) {
letter++; } else if (isdigit(str[i])) {
digit++;
} else if (isspace(str[i])) {
space++;
} else {
other++;
}
}
printf("字母个数:%d\n", letter);
printf("数字个数:%d\n", digit);
printf("空格个数:%d\n", space);
printf("其他字符个数:%d\n", other);
}
int main() {
char str[100];
printf("请输入字符串:");
gets(str);
count(str);
return 0;
}
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)