我有一个string
带有嵌入'\0'
字符的 c++。
我有一个函数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=[]