字符串的压缩strZig

思路:从第二个字符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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值