我的函数操作 std::string 会产生意外的结果
My function manipulating std::string's produces unexpected results
我正在尝试创建一个函数来查找子字符串的所有实例并将其替换为新字符串,但它似乎不起作用。这是代码:
#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);
相关文章:
- 尝试将字符串/字符转换为整数会产生意外结果
- RapidXML - 代码创建意外结果
- 类中静态函数C++意外结果
- 指针数组中的意外结果
- 使用指针访问数组元素时出现意外结果
- 使用 sprintf 和 %g 将双精度转换为字符串的意外结果
- C++:比较运算符>和字符串文本的意外结果
- 具有意外结果的 C++ 闭包
- yaml-cpp 比较的意外结果
- 每次都出现意外结果
- 在 Qt 中解析嵌套的 JSON 时出现意外结果(数组不存在)
- 如何避免 std::abs 的意外结果?
- 使用嵌套 if 语句的意外结果
- A ^= B ^= A ^= B;C# Visual Studio 中的意外结果
- 逻辑错误,我将获得意外结果
- 在 c++ 中使用异步的意外结果
- 从函数的返回值将元素C++存储到 std::vector 中时出现意外结果
- 执行递增和递减时"cout"链接会产生意外结果
- OpenCL - 内核方法返回意外结果
- C++使用 std::get_time 解析 YYMMDD ISO 8601 日期字符串会得到意外结果