思路:首先計算出有幾個不同的字符,再將每個字符的個數存在一個數組, 最後使用循環壓縮,定義i和j,一個指向放的位置,一個指向放的內容;
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void compress(char *p){
char *cur = p;
char *duff = p;
int count = 0;
int i = 0;
int j = 0;
int k = 0;
int len = strlen(p);
while (*duff++){ //計算有幾個不同的字符
while (*(duff) == *(duff + 1)){
duff++;
}
count++;
}
int *ptr = (int *)malloc(count*sizeof(int)); // 動態開闢存放每個元素個數的數組
if (ptr == NULL){
perror("use malloc");
exit(EXIT_FAILURE);
}
memset(ptr, 0, count*sizeof(int));
for (i = 0; i < count; i++){ // 計算數組的每個元素 (從0開始的)
while (*(cur) == *(cur + 1)){
ptr[i]++;
cur++;
}
cur++;
}
printf("%s\n", p);
for (k = 0; k < count; k++) //壓縮字符串
{
if (ptr[k] != 0){ //一個字符不用壓縮
for (i = 0, j = 0; j < len + 1; i++, j++){ //len+1 將'\0'賦值過去
if (p[j] == p[j + 1]){
p[i] = ptr[k] + '0' + 1; //將整形數字轉化爲字符型數字 加1因爲數組從0開始
j += ptr[k];
i++;
k++;
}
p[i] = p[j];
}
}
}
printf("%s\n",p);
free(ptr);
ptr = NULL;
}
int main(){
char str[] = "abbbbcccdddff";
// a4b3c3d2f
compress(str);
system("pause");
return 0;
}