gpt4 book ai didi

C++字符串压缩

转载 作者:行者123 更新时间:2023-11-28 03:34:24 24 4
gpt4 key购买 nike

我编写了一个程序,使用重复字符的计数来压缩字符串。如果压缩后的字符串比原始字符串长,那么我们仍然返回原始字符串。下面是我的程序:

void stringCompress(char* src) {
char* original;
original = src;
char* rst;
rst = src;

int histogram[256];
for (int i = 0; i < 256; i++) {
histogram[i] = 0;
}
int length = 0;
while (*src != NULL) {
length++;
src++;
}
src = original;
int j = 0;

for (int i = 0; i < length; i++) {

histogram[(int) src[i]]++;
if (histogram[(int) src[i]] == 1) {
rst[j] = src[i];

j++;

}

}
rst[j] = '\0';

char* final;

rst = original;
int index = 0;
char buffer[33];

for (int i = 0; i < j; i++) {

final[index] = rst[i];

stringstream number;
number<<histogram[(int)rst[i]];
-------> //cout<<number.str()<<endl;
char* temp = new char[number.str().length()+1];
strcpy(temp, number.str().c_str());
index++;
cout<<temp<<endl;
for(int k =0 ;k<number.str().length();k++)
{
final[index]=temp[k];
index++;

}

}

final[index] = '\0';
src = original;

if (index <= length) {
for (int i = 0; i < index; i++)

cout<<final[i];
} else {
cout << src << endl;
}

}

但奇怪的是,如果我离开 cout 语句 cout<<number.str()<<endl;有(箭头指向句子),那么输出就对了。例如,aaaabcdaa 输出 a6b1c1d1,aabcd 输出 aabcd。但是,如果我注释掉 cout<<number.str()<<endl; ,那么什么也不会生成。感谢您的帮助。

最佳答案

变量 final 在您的代码中未初始化。当我用内存缓冲区初始化它时,无论您指向的行是否被注释掉,您的程序都会打印所需的输出。

也许您打算使用buffer(未使用)作为final 的内存,例如:

final = buffer;

关于C++字符串压缩,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11495075/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com