C++字符串压缩
C++ string compress
我编写了一个程序,使用重复字符数压缩字符串。如果压缩后的字符串比原始字符串长,那么我们仍然返回原始字符串。以下是我的程序:
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] = ' ';
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] = ' ';
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;
相关文章:
- 连接和压缩标准::vector<std::字符串的最佳方法>
- 从我的2d数组中的一列返回的字符串值被压缩为一个字符串(在Mac os上打开Windows txt文件)
- 解压缩附加的压缩字符串
- 如何使用 Zstd 压缩C++字符串?
- 用Zlib解压缩文本字符串
- 可逆字符串压缩 PHP/C++
- 将参数包解压缩到字符串视图中
- 如何在C 中压缩字符串
- 使用 qCompress 使用 GZip 压缩字符串
- C++位操作:如何将char解码/解压缩为int,并显示正确的字符串
- 7zip 字符串/流压缩 PHP/C?存档中没有文件名/日期存储.7z每个字节都很重要
- 使用重复字符压缩字符串
- C++字符串压缩
- 简单的 zlib C++字符串压缩和解压缩
- 在位压缩字符串(C++)
- C++和zlib,有助于压缩字符串
- 用公共部件压缩字符串
- 无法使用sqlite3和C++解压缩从sql表中选择的压缩字符串
- 计算RLE压缩字符串所需的空间
- 使用zlib压缩字符串,命名文档