c 字符串压缩

#include <stdio.h>
#include <string.h>
//查找该元素是否已经存在 int find(char t[],int len,char ch) { int i; for(i = 0; i < len; i++) { if (t[i] == ch) { return 1; } } return 0; } char *CompressStr(char s[]) { char t[255]; int i = 0,j,k=0,count=1; while(s[i]) { j = i + 1; while ( s[j]) { if (s[i] == s[j]) { count++; //统计出现的次数 } j++; } int len = k; //数组长度 if ( find(t,len,s[i]) == 0) { t[k++] = count+'0'; //转换为字符保存 t[k++] = s[i]; //保存字符 } count = 1; //重置 i++; } t[k] = '\0'; strcpy(s,t); return s; } int main(int argc, char *argv[]) { printf("Hello, world\n"); char i,s[][20] = {"111225555","333AAAbbbb","ASdXDCdddddd","ababa"}; for(i = 0; i < 4; ++i) { printf("原串: %s\n",s[i]); printf("压缩后: %s\n",CompressStr(s[i])); } return 0; }

  

posted on 2015-06-19 17:32  嘘寒问暖  阅读(539)  评论(0编辑  收藏  举报

导航