每日一练6

字符串压缩与解压

  • 字符串压缩
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void test(char *buf,char **prnt)
{
    int res_len = 0, ori_len = 0;
    char *res = NULL;
    int i;
    char tmp_c = 0;
    int tmp_count=0;
    char tmpbuf[10];

    ori_len = strlen(buf);

    res = malloc(ori_len * 2);
    if (res == NULL)
        return;

    memset(res, 0, ori_len * 2);

    tmp_c = buf[0];
    for (i = 0; i < ori_len+1; i++)
    {
        if (tmp_c == buf[i])
            tmp_count++;
		
        else
        {
            memset(tmpbuf, 0, sizeof(tmpbuf));
            sprintf(tmpbuf, "%c%d", tmp_c, tmp_count);
            strcat(res, tmpbuf);
            tmp_c = buf[i];
            tmp_count = 1;
        }
    }

    res_len = strlen(res);

    if (res_len < ori_len)
        *prnt = res;
    else
        *prnt = buf;

}

int main(void)
{
    char buf[100];
    char *res = NULL;

    memset(buf, 0, sizeof(buf));
    scanf("%s",buf);

    test(buf,&res);
    printf("%s\n", res);

    return 0;
}


  • 字符串解压
int main1() 
{
	char str[256],str1[256];
	int i,j,k,n;
	
	scanf("%s",str); 
	i=j=0;
	while ( str[i] ) 
	{
		str1[j]=str[i];
		j++;
		i++;
		n=0;
		while ( str[i]>='0' && str[i]<='9' ) 
		{ 
			n*=10; 
			n+=str[i]-'0'; 
			i++; 
		}
	for ( k=0;k<n-1;k++ ) 
		str1[j+k]=str1[j-1];

    if ( n>0 ) 
		j+=n-1;
	}

	str1[j]=0;
	printf("%s\n",str1);

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值