[英]string::replace throws std::out_of_range on valid iterators
[英]std::out_of_range when using string find and replace inside while loop
因此,我有一个任务将某个字符串中某个单词的所有出现都转换为另一字符串。 但是while循环的条件存在问题,这会导致此错误
抛出'std :: out_of_range'实例后调用终止
what():basic_string :: replace
该应用程序已请求运行时以一种异常方式终止它。 请与应用程序的支持团队联系以获取更多信息。 进程返回3(0x3)执行时间:2.751 s
我的代码是:
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string str2("three");
string str("one three two four three three");
while ( str.find(str2) != NULL ){
str.replace(str.find(str2),str2.length(),"five");
cout << str << endl; // i put it inside loop to see output
}
cout << str << endl;
return 0;
}
有什么建议么?
您正在检查str.find(str2)
是否将其与NULL
进行比较,但这是错误的,因为NULL
是一个str.find(str2)
的宏,通常会扩展为0
,这可以是一个有效的索引。 您应该将其与std::string::npos
进行比较。 进行此更改后,您的代码即可使用。
编辑: std::string::npos
在18446744073709551615
测试时对应于18446744073709551615。 因此,这显然不是字符串中的有效索引。
这种情况
while ( str.find(str2) != NULL ){
这是没有意义的,因为调用find
可以返回不等于零的std::string::npos
。 在这种情况下,代码具有未定义的行为。
您可以采用以下方法
std::string str2("three");
std::string str("one three two four three three");
const char *five = "five";
size_t n = std::strlen(five);
for (std::string::size_type pos = 0;
( pos = str.find(str2, pos) ) != std::string::npos; pos += n)
{
str.replace(pos, str2.length(), five);
}
这是因为,如果str
不存在str2
则str.find(str2)
返回-1
。 您可以使用变量pos
来保存找到的位置,这样就无需重新调用find
函数。 该解决方案假定如下:
#include <iostream>
#include <string>
using namespace std;
int main () {
string str2("three");
string str("one three two four three three");
int pos = str.find(str2);
while (pos > 0) {
str.replace(pos, str2.length(), "five");
pos = str.find(str2);
cout << str << endl; // i put it inside loop to see output
}
cout << str << endl;
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.