统计一个输入的字符串中各个字符的个数 以及总字符个数

来源:互联网 发布:挪威知乎 编辑:程序博客网 时间:2024/05/21 10:05
//统计一个输入的字符串中各个字符的个数 以及总字符个数#include<stdio.h>int main(void){char str[80];char h[256]={0};int i=0;int countChar=0;int countWord=0;int flag=0;int temp=0;puts("Enter a string:");gets(str);while(str[i]){//统计单词个数if((str[i]>='a' && str[i]<='z') || (str[i]>='A' && str[i]<='Z') ||(str[i]>='0' && str[i]<='9') ) {flag=0;}else if(flag == 0){countWord++;flag=1;}//统计各个字符个数temp = str[i];if(temp != ' ') //统计字符总个数,不含空格{countChar++;}i++;h[temp]++;}printf("单词总数:%d\n",countWord);printf("字符总数:%d\n",countChar);for(i=0;i<256;i++){if(h[i]!=0){if(i==32)     //空格的ascii为32{printf("空格有%d个\n",h[i]);}elseprintf("%c%d个\n",i,h[i]);}}/*while(gets(str) != NULL && str[0]!='\0'){}*/}

原创粉丝点击