我需要在C++中对std::string进行简单的压缩和解压缩。我查看了这个网站,但是代码是针对字符数组的。我想要实现的是以下两个函数:
std::string original = "This is to be compressed!!!!";
std::string compressed = string_compress(original);
std::cout << compressed << std::endl;
std::string decompressed = string_decompress(compressed);
std::cout << decompressed << std::endl;
我曾经尝试使用boost压缩,方法如下:
std::string CompressData(const std::string &data)
{
std::stringstream compressed;
std::stringstream decompressed;
decompressed << data;
boost::iostreams::filtering_streambuf<boost::iostreams::input> out;
out.push(boost::iostreams::zlib_compressor());
out.push(decompressed);
boost::iostreams::copy(out, compressed);
return compressed.str();
}
std::string DecompressData(const std::string &data)
{
std::stringstream compressed;
std::stringstream decompressed;
compressed << data;
boost::iostreams::filtering_streambuf<boost::iostreams::input> in;
in.push(boost::iostreams::zlib_decompressor());
in.push(compressed);
boost::iostreams::copy(in, decompressed);
return decompressed.str();
}
但是代码有时会在字符串中产生空字符,即 \u0000。如果压缩数据包含这些空字符,我该如何处理?返回类型string正确吗?我如何使用zlib实现函数string_compress和string_decompress?
std::string
对于嵌入的 NUL 字符没有任何问题 - 你为什么会这样想呢? - sehe