【问题标题】:Remove null character embedded in string删除字符串中嵌入的空字符
【发布时间】: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


【解决方案1】:

它在您的情况下不起作用的原因是 std::string 构造函数来自 const char* 没有大小将读取所有元素,但不包括 nul 终止字符。结果,

 replaceAll(stringWithNull, "\0", "");

调用 replaceAll 并将 from 设置为空字符串 (replaceAll( string in, string from, string to )),返回未修改的 in

为了解决这个问题,使用一个带大小的构造函数,或者使用列表初始化进行初始化,就像你对原始字符串做的那样,例如:

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

【讨论】:

    【解决方案2】:

    当你这样做时

    replaceAll(stringWithNull, "\0", "");
    

    "\0""" 相同,因为std::string 的构造函数在从 c 字符串构造时停止在空字符处。这意味着你什么都没有寻找,什么都没有。你需要的是

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

    实际上得到from 填充了一个空字符。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-14
      • 2011-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多