gpt4 book ai didi

c++ - 替换字符串的二进制部分?

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

我有一个字符串,其中包含一些二进制数据。 xml 格式的字符串,所以在我处理它之前,我需要将二进制数据转换为 base64 格式。我正在使用一个名为 findXMLTag 的函数,它会在给定包含它的 xml 标记的情况下找到数据的开始和结束位置。现在我可以将该数据转换为 base64,但我在用新的 base64 数据替换旧的二进制数据时遇到问题。

问题是我不能使用任何类型的字符串,因为当它找到一个空字符时,它将把它视为字符串的终止点,但事实上,因为我在字符串中存储了二进制数据,所以那个空字符可以是我的二进制数据的一部分。

所以我想我正在寻找某种二进制替代品,但我不知道如何让它工作。在此先感谢您提供的任何帮助。

这是我用来定位 xml 字符串中数据的开始和结束的代码。

std::vector<TForm1::Pair> TForm1::findXMLTag(char *XMLString, char* XMLTag, int XMLSize)
{
void *found = XMLString;
int XMLTagLen = strlen(XMLTag);
std::vector<TForm1::Pair> result;
TForm1::Pair pair;
AnsiString XMLTagEnd = "</";
XMLTagEnd += &XMLTag[1];

while(found = memmem(XMLString, XMLSize - ((char*)found - XMLString), XMLTag, XMLTagLen))
{
if(found == NULL)
return result;

found = (char*)found + XMLTagLen;

pair.start = int((char*)found - XMLString);

found = memmem(found, XMLSize - ((char*)found - XMLString), XMLTagEnd.c_str(), XMLTagEnd.Length());

pair.end = int((char*)found - XMLString);

found = (char*)found + XMLTagEnd.Length();

result.push_back(pair);
}

return result;
}

最佳答案

将您的 C 风格答案转换为 C++,我们得到一个安全(对于有效索引)、高效且可读的一行:

std::string binary_replace(
std::string const& bin, unsigned bin_start, unsigned bin_end,
std::string const& replace_with
) {
assert(bin_start < bin.size() and bin_end < bin.size());
return bin.substr(0, bin_start) + replace_with + bin.substr(bin_end);
}

这可以通过使用 replace function 变得更加简单为此目的:

std::string binary_replace(
std::string bin, unsigned bin_start, unsigned bin_end,
std::string const& replace_with
) {
assert(bin_start < bin.size() and bin_end < bin.size());
return bin.replace(bin_start, bin_end - bin_start, replace_with);
}

(注意 bin 是按值传递的,因为 replace 修改了它。)

本质上,C++ 中的大多数 C 字符串函数都有一个直接替代品——在这种情况下,请查看 documentation of std::basic_string::substr .

关于c++ - 替换字符串的二进制部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19505174/

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