我的函数操作 std::string 会产生意外的结果

My function manipulating std::string's produces unexpected results

本文关键字:意外 结果 string 函数 操作 std 我的      更新时间:2023-10-16

我正在尝试创建一个函数来查找子字符串的所有实例并将其替换为新字符串,但它似乎不起作用。这是代码:

#include <string>
#include <windows.h>
void ReplaceSubstr(std::string mainstring, std::string substring1, std::string substring2)
{
    while (1)
    {
    int pos1 = mainstring.find (substring1);
    if (pos1 == -1)
        {
        return;
        }
    mainstring.erase(pos1, substring1.size());
    mainstring.insert(pos1, substring2);
    MessageBox (NULL, "successfully ran", NULL, NULL);
    }
}
int main()
{
    std::string target = "this string needs fixing";
    std::string bereplaced = "needs fixing";
    std::string replacement = "is fixed";
    ReplaceSubstr (target, bereplaced, replacement);
    MessageBox (NULL, target.c_str(), NULL, NULL);
    return 0;
}

运行代码时会出现 2 个MessageBox,第一个带有文本"已成功运行",然后另一个带有文本"此字符串需要修复"。我期望的是第二个MessageBox出现文本"此字符串已修复"。

发布的代码有两个问题:

  • 调用 std::string::erase 会使所有迭代器失效,即一旦成员函数返回,pos1就不能再使用(请参阅此答案(。
  • 您是按传递参数的,因此任何修改都仅反映在本地临时副本中。

第一个问题特别令人讨厌,因为它经常看起来有效。但是,它仍然是未定义的行为,需要解决(通过使用返回有效迭代器的 std::string::erase 重载,或者调用 std::string::replace 代替(。

第二个问题也可以通过两种方式解决,要么通过引用传递第一个参数,要么返回一个新的字符串对象。

解决方案可能如下所示:

std::string ReplaceSubstr( const std::string& input, const std::string& pattern,
                                                     const std::string& replacement ) {
    std::string output{ input };
    auto pos = output.find( pattern );
    while ( pos != std::string::npos ) {
        output.replace( pos, pattern.size(), replacement );
        pos = output.find( pattern );
    }
    return output;
}

如果要就地执行替换,只需将返回类型更改为 void ,将第一个参数替换为对 non-const 的引用,并将 input 用于所有出现的output(减去最终的 return 语句(。

你可以通过以下方式轻松做到这一点:-

 index = target.find(bereplaced.c_str(), index);
 if (index == string::npos) 
     //return or do something else
 target.replace(index, replacement.size(), replacement);