思路:从第二个字符q开始判断是否等于前一个字符p,如果相等,则q继续向后跑
如果不相等,如果只有一个相同字符,则直接填入k中,否则由q-p得到相同字符的个数dif,
借由第三个字符串变量k,存放数字和相应的字符,首先判断数字的位数,
再判断数字个位应填入的位置,--k
一次放入数字字符,再得到填入字符的位置放入字符。
字符串压缩程序:
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
void stringZip(const char* pInputStr,long lInputLen,char *pOutputStr)
{
const char *p = pInputStr;
const char *q = pInputStr + 1; //
定义q从第二个字符开始。
char *k = pOutputStr;
while(*p != '\0')
{
if(*p != *q)
{
int dif = q - p; //
相隔几个字符
if(dif > 1)
{
int count = 0;
int num = dif;
while(num)
{
num = num/10;
count++;
}
k += count - 1; //判断相同的字符个数从k的哪一位开始输入 0, 1 , 2.........
while(dif)
{
int mod = dif % 10;
*k = '0' + mod;
--k;
dif = dif / 10;
}
k += count + 1; // 依次将相同个数的值按个位,十位》,输入到k中。
}
*k++ = *p;
p = q++; //将字符写入k中。
}
else
{
++q;
}
}
*k = '\0';
}
int main()
{
char *src = "aabbbcddde";
char *des =(char *)malloc(strlen(src)+1); //
malloc一个与源串空间大小相同的目的串。
stringZip(src,strlen(src),des);
printf("outputstring:%s\n",des);
return 0;
}