删除嵌入在字符串中的空字符

Lev*_*viX 0 c++ string null-character

我有一个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());
}
Run Code Online (Sandbox Code Playgroud)

输出:

size=[4] data=[]
size=[4] data=[]
Run Code Online (Sandbox Code Playgroud)

Ser*_*eyA 5

它在你的情况下不起作用的原因是std::string来自const char*无大小的构造函数将读取所有元素,但不包括nul-terminateding char.结果是,

 replaceAll(stringWithNull, "\0", "");
Run Code Online (Sandbox Code Playgroud)

调用replaceAllfrom设置为空字符串(replaceAll( string in, string from, string to )),它返回in不变.

要解决此问题,请使用一个构造函数,该构造函数需要大小,或者使用列表初始化进行初始化,就像对原始字符串执行一样,例如:

replaceAll(stringWithNull, {'\0'}, "");
Run Code Online (Sandbox Code Playgroud)