c语言统计字符串中数字个数的方法
时间: 2024-03-24 18:14:09 浏览: 77
可以使用循环遍历字符串中的每个字符,判断是否是数字,如果是数字则计数器加1。具体实现如下:
```c
#include <stdio.h>
int count_digit(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[] = "Hello 123 World!";
int count = count_digit(str);
printf("The number of digits in the string is: %d\n", count);
return 0;
}
```
运行结果:
```
The number of digits in the string is: 3
```
注意:此方法只能统计纯数字的个数,如果字符串中包含其他字符(如字母、符号等),则不能正确统计。
相关问题
c语言统计字符串中字母个数数字空格其他字符
好的,针对您的问题,我可以给您提供以下的 C 语言代码来统计一个字符串中字母、数字、空格和其他字符的个数:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int i, alphabets, digits, spaces, others;
alphabets = digits = spaces = others = 0;
printf("请输入一个字符串:");
fgets(str, sizeof(str), stdin);
for(i = 0; str[i] != '\0'; i++) {
if(isalpha(str[i])) {
alphabets++;
} else if(isdigit(str[i])) {
digits++;
} else if(str[i] == ' ') {
spaces++;
} else {
others++;
}
}
printf("字母个数:%d\n", alphabets);
printf("数字个数:%d\n", digits);
printf("空格个数:%d\n", spaces);
printf("其他字符个数:%d\n", others);
return 0;
}
```
这段代码中使用了 `isalpha()`、`isdigit()` 等函数来判断一个字符是否为字母或数字,同时也判断了空格和其他字符。您可以将输入的字符串改成您需要统计的字符串。
C语言统计字符串中数字字符的个数
可以使用C语言中的循环和判断语句来统计字符串中数字字符的个数。具体方法如下:
```c
#include <stdio.h>
int main() {
char str[100];
int count = 0, i;
printf("请输入一个字符串:");
scanf("%s", str);
for (i = 0; str[i] != '\0'; i++) {
if (str[i] >= '0' && str[i] <= '9') {
count++;
}
}
printf("字符串中数字字符的个数为:%d\n", count);
return 0;
}
```
这段代码首先定义了一个字符数组 `str` 和一个整型变量 `count`,用于存储输入的字符串和统计数字字符的个数。然后使用 `scanf()` 函数从标准输入中读取一个字符串。接下来使用 `for` 循环遍历字符串中的每个字符,如果字符是数字字符,则将计数器 `count` 加 1。最后输出统计结果。
希望可以帮到您!
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.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)