c语言编写一个函数,接收一个字符串,统计其中数字字符个数及字母字符个数
时间: 2023-12-28 08:05:03 浏览: 36
可以使用C语言中的字符处理函数isalpha()和isdigit()来判断字符是字母还是数字。以下是一个示例函数:
```c
#include <stdio.h>
#include <ctype.h>
void count(char *str)
{
int letters = 0, digits = 0;
while (*str)
{
if (isalpha(*str))
letters++;
else if (isdigit(*str))
digits++;
str++;
}
printf("字母个数:%d\n数字个数:%d\n", letters, digits);
}
int main()
{
char str[100];
printf("请输入一个字符串:");
scanf("%s", str);
count(str);
return 0;
}
```
该函数首先声明了两个变量letters和digits分别用于记录字母和数字的个数,然后使用while循环遍历字符串中的每一个字符,使用isalpha()和isdigit()函数判断字符是否为字母或数字,如果是则对应计数变量加1。最后输出字母和数字的个数即可。
相关问题
c语言编写一个函数,接收一个字符串,统计其中数字字符个数及字母字符个数。函数原
本可以如下编写:
```c
#include <stdio.h>
#include <ctype.h>
void countCharacters(char *str) {
int numCount = 0;
int letterCount = 0;
while(*str) {
if(isdigit(*str)) {
numCount++;
} else if(isalpha(*str)) {
letterCount++;
}
str++;
}
printf("数字字符个数:%d\n", numCount);
printf("字母字符个数:%d\n", letterCount);
}
int main() {
char input[100];
printf("请输入一个字符串:");
scanf("%s", input);
countCharacters(input);
return 0;
}
```
这个函数接收一个字符串作为参数,然后遍历这个字符串,通过isdigit()和isalpha()函数来判断其中的数字字符和字母字符,分别累加计数。最后在主函数中调用这个函数,输出统计结果。
C语言 编写函数,统计一个字符串中包含的数字字符的个数
可以编写一个函数来实现这个功能,函数的参数为字符串指针,返回值为数字字符的个数。具体实现如下:
```c
int count_digits(char* str) {
int count = 0;
while (*str != '\0') {
if (*str >= '0' && *str <= '9') {
count++;
}
str++;
}
return count;
}
```
函数中使用了一个 while 循环,遍历字符串中的每个字符,如果该字符是数字字符,则计数器加一。最后返回计数器的值即可。在主函数中调用该函数,传入需要统计数字字符的字符串即可。
例如:
```c
#include <stdio.h>
int count_digits(char* str);
int main() {
char str[] = "abc12345xyz";
int count = count_digits(str);
printf("The number of digits in the string is: %d\n", count);
return 0;
}
int count_digits(char* str) {
int count = 0;
while (*str != '\0') {
if (*str >= '0' && *str <= '9') {
count++;
}
str++;
}
return count;
}
```
输出结果为:
```
The number of digits in the string is: 5
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)