一个字符串压缩程序

题目描述:
通过键盘输入一串小写字母(a~z)组成的字符串。请编写一个字符串压缩程序,将字符串中连续出席的重
复字母进行压缩,并输出压缩后的字符串。
压缩规则:
1. 仅压缩连续重复出现的字符。比如字符串"abcbc"由于无连续重复字符,压缩后的字符串还是"abcbc".
2. 压缩字段的格式为"字符重复的次数+字符"。例如:字符串"xxxyyyyyyz"压缩后就成为"3x6yz"
要求实现函数:
void stringZip(const char *pInputStr, long lInputLen, char *pOutputStr);
【输入】pInputStr: 输入字符串
lInputLen: 输入字符串长度
【输出】pOutputStr: 输出字符串,空间已经开辟好,与输入字符串等长;
【注意】只需要完成该函数功能算法,中间不需要有任何IO 的输入输出示例2
输入:“cccddecc” 输出:“3c2de2c”
输入:“adef” 输出:“adef”

输入:“pppppppp” 输出:“8p”

#include <stdio.h>
#include <string.h>
void stringZip(const char *pInputStr, long lInputLen, char *pOutputStr){
	int count = 0;//记录字符出现的次数
	char temp;
	int i, j;
	temp = pInputStr[0];
	count++;
	for(i =1; i <lInputLen; i++){
		if(pInputStr[i] == temp){	//与前一个字符相等
			count++;
		}else{//与前一个字符不等
			if(count == 1){//出现一次
				*pOutputStr = temp;
				pOutputStr++;
				count = 1;//因为是与之前的字符不相等,所以计数从1开始
			}else{//出现多次
				*pOutputStr = count + '0';//将数字转化成字符
				pOutputStr++;
				*pOutputStr = temp;
				pOutputStr++;
				count = 1;
			}
		}
		temp = pInputStr[i];
	}
	if(count == 1){//出现一次
		*pOutputStr = temp;
		pOutputStr++;
		count = 1;//因为是与之前的字符不相等,所以计数从1开始
	}else{//出现多次
		*pOutputStr = count + '0';//将数字转化成字符
		pOutputStr++;
		*pOutputStr = temp;
		pOutputStr++;
		count = 1;
	}
	*pOutputStr = '\0';
}
void main(){
	char input[100];
	char output[100];
	int len;
	strcpy(input, "xpppppppaaaa");
	printf("%s\n", input);
	len = strlen(input);
	stringZip(input, len, output);
	printf("%s\n", output);
	getchar();
}

【出错记录】没有输出最后一组字符。因为对于pOutput修改是在出现不同字符时进行,所以最后一组并没有输出,需要单独输出。

再次看到这个程序的时候,感觉在stringZip()函数中,跳出循环后又一次出现判断、生成字符串,十分冗余,改进如下:

void stringZip(const char *in, long len, char *out){
	int i;
	int count = 1;
	char temp = *in;
	for(i = 1; i <= len; i++){//此处将结束条件改为<=len
		if(temp == in[i]){
			count++;
		}else{
			if(count == 1){
				*out = in[i-1];
				out++;
			}else{
				*out = count + '0';
				out++;
				*out = in[i -1 ];
				out++;
			}
			count = 1;
			temp = in[i];
		}
	}//将重复的删除
	*out = '\0';
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值