gpt4 book ai didi

c++ - 使用C++进行行程解压缩

转载 作者:行者123 更新时间:2023-12-02 10:05:41 26 4
gpt4 key购买 nike

我有一个带有编码字符串的文本文件。

假设它是:aaahhhhiii kkkjjhh ikl wwwwwweeeett
这是用于编码的代码,可以很好地工作:

void Encode(std::string &inputstring, std::string &outputstring)
{
for (int i = 0; i < inputstring.length(); i++) {
int count = 1;
while (inputstring[i] == inputstring[i+1]) {
count++;
i++;
}
if(count <= 1) {
outputstring += inputstring[i];
} else {
outputstring += std::to_string(count);
outputstring += inputstring[i];
}
}
}

输出符合预期: 3a4h3i 3k2j2h ikl 6w4e2t
现在,我想将输出解压缩-回到原始状态。

从现在开始,我一直在为此苦苦挣扎。

到目前为止,我的想法是:
void Decompress(std::string &compressed, std::string &original)
{
char currentChar = 0;
auto n = compressed.length();
for(int i = 0; i < n; i++) {

currentChar = compressed[i++];

if(compressed[i] <= 1) {
original += compressed[i];
} else if (isalpha(currentChar)) {
//
} else {
//
int number = isnumber(currentChar).....
original += number;
}
}
}

我知道我的Decompress函数似乎有点困惑,但是我对此感到很迷惑。
抱歉

也许在stackoverflow上有人愿意帮助失落的初学者。

多谢您的协助,不胜感激。

最佳答案

#include "string"
#include "iostream"


void Encode(std::string& inputstring, std::string& outputstring)
{
for (unsigned int i = 0; i < inputstring.length(); i++) {
int count = 1;
while (inputstring[i] == inputstring[i + 1]) {
count++;
i++;
}
if (count <= 1) {
outputstring += inputstring[i];
}
else {
outputstring += std::to_string(count);
outputstring += inputstring[i];
}
}
}

bool alpha_or_space(const char c)
{
return isalpha(c) || c == ' ';
}

void Decompress(std::string& compressed, std::string& original)
{
size_t i = 0;
size_t repeat;
while (i < compressed.length())
{
// normal alpha charachers
while (alpha_or_space(compressed[i]))
original.push_back(compressed[i++]);

// repeat number
repeat = 0;
while (isdigit(compressed[i]))
repeat = 10 * repeat + (compressed[i++] - '0');

// unroll releat charachters
auto char_to_unroll = compressed[i++];
while (repeat--)
original.push_back(char_to_unroll);
}
}

int main()
{
std::string deco, outp, inp = "aaahhhhiii kkkjjhh ikl wwwwwweeeett";

Encode(inp, outp);
Decompress(outp, deco);

std::cout << inp << std::endl << outp << std::endl<< deco;

return 0;
}

关于c++ - 使用C++进行行程解压缩,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60297299/

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