标题:字符串压缩
问题描述:有一种简单的字符串压缩算法,对于字符串中连续出现的同一个英文字符,用该字符加上连续出现的次数来表示(连续出现次数小于3时不压缩)。
主程序如下:
#include
#include
#include
char *compress(char *src);
int main()
{
char src[100];
scanf("%s",src);
char *ps = compress(src);
puts(ps);
return 0;
}
请设计一个程序,采用该压缩方法对字符串压缩并输出。请编写一个函数compress,采用该压缩方法对字符串src进行压缩。函数定义如下:
char *compress(char *src);
返回值:
指向压缩后的字符串数据
参数:
src:输入/输出参数,输入表示待压缩字符串,输出表示压缩后的字符串
注意:函数声明已包含在主程序中,不需要自己定义。只需要提交自定义的函数代码。
主函数输入说明:
输入第一行为源字符串src(长度小于100),该字符串只包含大小写字母。
主函数输出说明:
输出一个数据,表示压缩后的字符串。
贴过去试一试效果呢
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char *compress(char *src);
int main()
{
char src[100];
scanf("%s",src);
char *ps = compress(src);
puts(ps);
return 0;
}
char *compress(char *src)
{
char oldch = '\0';//前一个字符
char newch = '\0';//最新字符
char *newsrc = src;//在原来src字符串上面填充压缩后的字符串
char *returnsrc = src;//返回字符串到首地址
int count = 0 ;//记录连续次数
oldch = *src;//第一个字符串
while(*src != '\0')
{
newch = *src;
if(newch == oldch)
{
count++ ;//前一个字符与最新字符相同 计数加一
}
else
{ //不相同开始统计计算
if(count < 3)
{
if(count == 1)//计算为1 在新到字符串上填一个
{
*newsrc=oldch;
newsrc++;
}
else if(count == 2)//计数为2填两个
{
*newsrc=oldch;
newsrc++;
*newsrc=oldch;
newsrc++;
}
}
else//计数大于3
{
*newsrc=oldch;//填充旧字符和压缩的数值
newsrc++;
if(count /10)//计算大于10的情况
{
*newsrc='0'+count/10;
newsrc++;
}
*newsrc='0'+count%10;
newsrc++;
}
count = 1;//当前新字符计数1
oldch = newch;
}
src++; //字符串向后滚动
}
if(count < 3)//填充最后字符计算情况 如 abcddddd, 最后d也要统计
{
if(count == 1)
{
*newsrc=oldch;
newsrc++;
}
else if(count == 2)
{
*newsrc=oldch;
newsrc++;
*newsrc=oldch;
newsrc++;
}
}
else
{
*newsrc=oldch;//填充旧字符和压缩的数值
newsrc++;
if(count /10)
{
*newsrc='0'+count/10;
newsrc++;
}
*newsrc='0'+count%10;
newsrc++;
}
//截断字符串,丢弃原来没有压缩的字符串
*newsrc = '\0';
return returnsrc;
}
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char *compress(char *src)
{
int count = 1;
char temp = 0;
char mark = 0;
char *p = src;
static char dst[100] = {0};
int index = 0;
char press[10] = {0};
int flag = 0;
memset(dst, 0, sizeof(dst));
while(*p != '\0')
{
if(flag == 0)
{
temp = *p;
mark = *p;
p++;
flag = 1;
continue;
}
if(temp == *p)
{
count++;
mark = *p;
}else{
memset(press, 0, sizeof(press));
if(count == 1)
{
dst[index++] = mark;
}else if(count == 2)
{
dst[index++] = mark;
dst[index++] = mark;
}else{
sprintf(press, "%d%c", count, mark);
memcpy(dst + index, press, strlen(press));
index += strlen(press);
}
temp = *p;
mark = *p;
count = 1;
}
p++;
}
memset(press, 0, sizeof(press));
if(count == 1)
{
dst[index++] = mark;
}else if(count == 2)
{
dst[index++] = mark;
dst[index++] = mark;
}else{
sprintf(press, "%d%c", count, mark);
memcpy(dst + index, press, strlen(press));
index += strlen(press);
}
return dst;
}
int main()
{
char src[100];
scanf("%s",src);
char *ps = compress(src);
puts(ps);
return 0;
}