我有一个大字符串 char myStr="AAAABBBCCCCCCDDDEFGHHIJJ"。 我将把这个字符串传递给我的字符串压缩函数,它应该以下面的格式返回我的字符串 myStr ="A4B3C6D3EFGH2IJ2" 此外,新的字符串替换应该只发生在相同的传递字符串中。不能创建临时数组。
下面是我的函数,我无法找出删除重复项并替换为同一字符串中的计数。
#include<stdio.h>
#include<string.h>
char* StrCompress(char myStr[])
{
char *s = myStr;
int len = strlen(myStr);
char *in = myStr;
int count =0;
int i=0;
while(*(s) != '\0')
{
if(*(s)==*(s+1))
{
count++;
if(count == 1)
{
in = s;
}
s++;
}
else
{
//myStr[count-1]=count;
memcpy(in+1,s+1,count);
s=in;
count =0;
}
i++;
}
return myStr;
}
int main(){
char myStr[] ="AAAABBBCCCCCEEFGIIJJJKLMNNNNOOO";
printf("Compressed String is : %s\n",StrCompress(&myStr));
return 0;
}
最佳答案
稍作修改的版本:
char* StrCompress(char myStr[])
{
char *s, *in;
for (s = myStr, in = myStr; *s; s++) {
int count = 1;
in[0] = s[0]; in++;
while (s[0] == s[1]) {
count++;
s++;
}
if (count > 1) {
int len = sprintf(in, "%d", count);
in += len;
}
}
in[0] = 0;
return myStr;
}
此外,在调用数组名时不应该使用运算符的地址:
StrCompress(myStr); // not StrCompress(&myStr)
如果您假设一个字符不能重复超过 9 次,那么您可以使用 in[0] = '0' + count
而不是 sprintf
内容:
if (count > 1) {
in[0] = '0' + count;
in++;
}
关于c - 如何使用 C 压缩字符串并用其计数替换重复项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14037263/