删除字符串中嵌入的空字符 我有一个C++代码>字符串嵌入的代码> > 0”< /代码>字符。

删除字符串中嵌入的空字符 我有一个C++代码>字符串嵌入的代码> > 0”< /代码>字符。,c++,string,null-character,C++,String,Null Character,我有一个函数replaceAll(),它应该用另一个模式替换一个模式的所有出现。对于“正常”字符串,它可以正常工作。但是,当我试图查找'\0'字符时,我的函数不起作用,我不知道为什么replaceAll似乎在string::find()上失败,这对我来说毫无意义 // Replaces all occurrences of the text 'from' to the text 'to' in the specified input string. // replaceAll("Foo123Fo

我有一个函数
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=[]

在您的例子中,它不起作用的原因是来自
const char*
std::string
构造函数(不带大小)将读取所有元素,但不包括nul终止字符。因此,

 replaceAll(stringWithNull, "\0", "");
调用
replaceAll
,将
from
设置为空字符串(
replaceAll(string-in,string-from,string-to)
),返回未经修改的

要解决此问题,请使用具有大小的构造函数,或使用列表初始化进行初始化,与对原始字符串进行初始化的方式相同,例如:

replaceAll(stringWithNull, {'\0'}, "");

在您的例子中,它不起作用的原因是来自
const char*
std::string
构造函数(不带大小)将读取所有元素,但不包括nul终止字符。因此,

 replaceAll(stringWithNull, "\0", "");
调用
replaceAll
,将
from
设置为空字符串(
replaceAll(string-in,string-from,string-to)
),返回未经修改的

要解决此问题,请使用具有大小的构造函数,或使用列表初始化进行初始化,与对原始字符串进行初始化的方式相同,例如:

replaceAll(stringWithNull, {'\0'}, "");
当你这样做的时候

replaceAll(stringWithNull, "\0", "");
“\0”
相同,因为
std::string
的构造函数在从c字符串构造时停止在空字符处。这意味着你什么都不找,什么都不找。你需要的是

string replaced = replaceAll(stringWithNull, {'\0'}, "");
从填充了空字符的
中实际获取

当您这样做时

replaceAll(stringWithNull, "\0", "");
“\0”
相同,因为
std::string
的构造函数在从c字符串构造时停止在空字符处。这意味着你什么都不找,什么都不找。你需要的是

string replaced = replaceAll(stringWithNull, {'\0'}, "");

要从填充了空字符的
中实际获取

是否调试了它以查看循环是否真的在查找字符?顺便说一句,您应该实际搜索字符本身,而不是字符串。@MatthieuBrucher为什么要搜索字符?这限制了功能。如果我想重新体验所有发生在
“:)”
中的
:):::::::::::):)“
如果我不能指定
“:)”
作为替换对象,那将是一件非常痛苦的事情。你调试它是为了看看你的循环是否真的找到了角色吗?顺便说一句,你应该实际搜索角色本身,不是字符串。@MatthieuBrucher为什么要搜索字符?这限制了功能。如果我想重新体验所有发生在
“:)”
中的
:)::::::::::):):“
如果我不能指定
“:)”
作为替代品,那将是一个真正的痛苦。