【发布时间】:2019-04-11 02:03:08
【问题描述】:
我有一个嵌入了 '\0' 字符的 c++ string。
我有一个函数replaceAll(),应该用另一个模式替换所有出现的模式。对于“普通”字符串,它工作正常。但是,当我尝试查找 '\0' 字符时,我的功能不起作用,我不知道为什么。 replaceAll 似乎在 string::find() 上失败了,这对我来说没有意义。
// Replaces all occurrences of the text 'from' to the text 'to' in the specified input string.
// replaceAll("Foo123Foo", "Foo", "Bar"); // Bar123Bar
string replaceAll( string in, string from, string to )
{
string tmp = in;
if ( from.empty())
{
return in;
}
size_t start_pos = 0;
// tmp.find() fails to match on "\0"
while (( start_pos = tmp.find( from, start_pos )) != std::string::npos )
{
tmp.replace( start_pos, from.length(), to );
start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
}
return tmp;
}
int main(int argc, char* argv[])
{
string stringWithNull = { '\0', '1', '\0', '2' };
printf("size=[%d] data=[%s]\n", stringWithNull.size(), stringWithNull.c_str());
// This doesn't work in the special case of a null character and I don't know why
string replaced = replaceAll(stringWithNull, "\0", "");
printf("size=[%d] data=[%s]\n", replaced.size(), replaced.c_str());
}
输出:
size=[4] data=[]
size=[4] data=[]
【问题讨论】:
-
您是否调试过它以查看您的循环是否真的找到了角色?
-
顺便说一句,您实际上应该搜索字符本身,而不是字符串。
-
@MatthieuBrucher 为什么要搜索字符?这限制了功能。如果我想从
":) :) :) :::too many smiles::: :) :) :)"重新出现":)"的所有出现,如果我不能将":)"指定为要替换的东西,那将是一个真正的痛苦。
标签: c++ string null-character