【发布时间】:2015-02-12 20:12:09
【问题描述】:
我正在尝试创建一个函数来查找子字符串的所有实例并将其替换为新字符串,但它似乎不起作用。代码如下:
#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 MessageBoxs 在代码运行时出现,第一个带有文本“成功运行”,然后另一个带有文本“此字符串需要修复”。我的预期是第二个MessageBox 出现“此字符串已修复”文本。
【问题讨论】:
-
如果替换相同,这将挂起。
-
您正在传递字符串按值。
-
@Joachim Pileborg 谢谢,我不敢相信我错过了。如果您将其添加为答案,我会接受并投票。
标签: c++ string winapi stdstring