压缩字符串,input:aaabbbccc output:3a3b3c
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 char* compress(const char * src, char *des) 5 { 6 if (des==NULL) 7 { 8 return NULL; 9 } 10 int count = 1; 11 int pointer = 0; 12 char current = src[0]; 13 int i; 14 for (i=1; i<strlen(src); i++) 15 { 16 if (src[i]==current) 17 { 18 count++; 19 }else{ 20 pointer += sprintf(&des[pointer], "%d", count); 21 des[pointer++] = current; 22 count = 1; 23 current = src[i]; 24 } 25 } 26 pointer += sprintf(&des[pointer], "%d", count); 27 des[pointer++] = current; 28 des[pointer] = '\0'; 29 return des; 30 } 31 32 int main() 33 { 34 char arr[100]; 35 char brr[201]; 36 while(1) 37 { 38 scanf("%s", arr); 39 printf("%s\n", compress(arr, brr)); 40 } 41 return 0; 42 }