本题要求实现一个字符串压缩的简单函数。压缩规则是:如果某个字符x
连续出现n
(n>1)次,则将这n
个字符x
替换为nx
的形式;否则保持不变。
函数接口定义:
void zip( char *p );
函数zip
对p
指向的字符串进行压缩操作。
代码:
#include <stdio.h>
#define MAXS 20
void zip(char *p)
{
int m,j=0,count=1;
int len=strlen(p);
for(m=0;m<len;m++)
{
if(p[m]==p[m+1])
count++;
else{
if(count==1)
{
p[j]=p[m];
j++;
}
if(count>1&&count<10)
{
p[j]=count+48; //加上48后就是数字对应的字符型
j++;
p[j]=p[m];
j++;
count=1;
}
else if(count>9)
{p[j]=(count/10)+48;
j++;
p[j]=(count%10)+48;
j++;
p[j]=p[m];
j++;
count=1;
}
}
}
p[j]='\0';
}
void ReadString( char *s ); /* 由裁判实现,略去不表 */
int main()
{
char s[MAXS];
ReadString(s);
zip(s);
printf("%s\n", s);
return 0;
}
/* 请在这里填写答案 */