5,530
社区成员
发帖
与我相关
我的任务
分享
#ifndef COMPRESS_STRING_H
#define COMPRESS_STRING_H
#include <string>
#include <map>
#include <iostream>
using namespace std;
class CompressedString {
private:
map<char,int> characterSet; //构建字符字典
int bitSize; //压缩单个字符后所占二进制位
public:
CompressedString(string); //通过字符集构造
string compress(const string& str); //压缩字符串
string uncompress(const string& cp); //解压缩
void setCharacterSet(const string& s); //设置字符集
void display(const string& s); //输出对比
};
#endif // COMPRESS_STRING_H
源文件
#include "CompressedString.h"
CompressedString::CompressedString(string s){
setCharacterSet(s);
}
string CompressedString::compress(const string& raw)
{
string cps(round(raw.size() * (double)bitSize / 8) + 1, ' ');
char ch = 0;
int index = 0;
int pos = 0;
for (int i = 0; i < raw.size(); i++) {
for (int j = 0; j <bitSize; j++) {
ch |= ((characterSet.at(raw[i])>>j) & 1)<<(index++);
if (index == 8) {
cps[pos++]=(ch);
index = ch = 0;
}
}
}
if (index != 0) //当有剩余bit时
cps[pos++] = (ch);
cps[pos++] = index ? 8 - index : 8; //记录末尾bit
return cps;
}
string CompressedString::uncompress(const string& cp)
{
string uncp(((cp.size()-1)*8-(8-cp.back()))/bitSize,' ');
int index = 0;
int pos = 0;
for (int i = 0; i < cp.size()-1;) {
int c = 0;
for (int j = 0; j < bitSize; j++) {
c |= (((cp[i] >> index++) & 1) << j);
if (index == 8) {
i++;
if (i >= cp.size()-1)
break;
index = 0;
}
}
if(pos<uncp.size())
uncp[pos++]=((next(characterSet.begin(), c))->first);
}
return uncp;
}
void CompressedString::setCharacterSet(const string& s)
{
for (int i = 0; i < s.size(); i++)
characterSet.insert({ s[i],i });
bitSize = ceil(log2(s.size()));
}
void CompressedString::display(const string& s)
{
cout << "原始字符串:" << s << "\t压缩字符串:[" << compress(s) << "]\t解压缩字符串:[" << uncompress(compress(s)) << "]" << endl;
}
#include <iostream>
#include "CompressedString.h"
#include <string>
using namespace std;
int main() {
CompressedString s("0123456789ABCDEF");
s.display("123456789");
s.display("123445635464564532546ADCFEA");
wstring str = L"123456" ;
return 0;
}