1. 打印输入中单词长度
2. 打印输入中各个字符出现频度的直方图
#include <stdio.h> #include <Conio.h> #include <stdlib.h> #define IN 1 #define OUT 0 main() { int nc, nw, count, state, input; int nclist[26]; for (int i = 0; i< 26; ++i){ nclist[i] = 0; } nc = nw = count = 0; int* nwlist = (int*)calloc(nw,sizeof(int)); state = OUT; while((input=getchar())!=EOF){ ++nc; ++nclist[input-'a']; if (state == IN){ nwlist [nw-1] = ++count; } if(input == ' ' || input == '\t'|| input == '\n'){ state = OUT; count = 0; }else if(state == OUT){ state = IN; ++nw; nwlist = (int *)realloc(nwlist, 1*sizeof(int)); } } printf("************below is word length details***********\n"); for(int i = 0; i < nw; ++i){ printf("%d\n",nwlist[i]); } printf("************below is character details************\n"); for(int i = 0; i < 26; ++i){ printf("%c: ", ('a'+ i)); for(int j = 0; j< nclist[i]; ++j){ printf("*"); } printf("\n"); } getch(); }
结果:
tips:
C语言中数组动态分配int
* a=(
int
*)
calloc
(n,
sizeof
(
int
));
//n是数组的大小。
需要导入<stdlib.h>包。本例在不考虑效率的情况下也可以申请一个足够大的数组。