C语言编写函数实现字符串中各类字符数目的统计

时间:2025-04-20 07:39:24

问题描述

编写一个函数,用实参传来一个字符串,统计此字符串中字母、数字、空格和其他字符的个数,在主函数中输入字符串以及输出上述的结果

解决办法

代码如下

#include<>  
#include<>  
#include<>  
 
//定义全局变量  
int letter = 0;  //字母  
int number = 0;  //数字  
int space = 0;  //空格  
int others = 0;  //其他  
  
//定义统计函数  
void len_txt(char s[])  
{  
    int c;  
    int i;  
  
    c = strlen(s);  //获取字符串的长度  
  
    //分别判断  
    for (i = 0;i < c;i++){  
 
        if (isalpha(s[i]))  
        {  
            letter++;  
        }  
        else if (isdigit(s[i]))  
        {  
            number++;  
        }  
        else if (s[i] == ' ')  
        {  
            space++;  
        }  
        else  
        {  
            others++;  
        }  
    }  
  
}  
  
//主函数  
int main()  
{  
  
    char s[100];  //定义字符串最大长度  
    printf("请输入字符串:");  
    gets(s);  //获取字符串  
    len_txt(s);  //调用函数  
    printf("\n统计结果:\n字母=%d \n数字=%d \n空格=%d \n其他=%d",letter,number,space,others);  
  
    return 0;  
  
}  

到此为止。