2016-12-29 167 views
1

所以我有一个任务将一个字符串中的某个字的所有出现转换为另一个字符串。但与while循环的条件问题,这使得这个错误std :: out_of_range当使用字符串查找和替换内循环

终止叫做抛出“的std :: out_of_range”

什么()的一个实例后:basic_string的::替换

此应用程序已经要求运行时以不寻常的方式终止它。请联系应用程序支持团队以获取更多信息。流程返回3段(0x3)执行时间:2.751小号

我的代码是:

#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; 
} 

有什么建议?

回答

3

您检查是否有str.find(str2)发生比较它NULL,但这是错误的,因为NULL是不是意味着这一点,往往扩展到0,其中可以是一个有效的索引的宏。您应该将其与std::string::npos进行比较。完成这一更改后,您的代码将起作用。

编辑:std::string::npos对应于在coliru上测试时的18446744073709551615。所以这显然不是你的字符串中的有效索引。

+0

感谢您的帮助。 – DoktorD96

1

这种情况

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); 
} 
0

它造成的,因为str.find(str2)回报-1如果str2没有在str存在。您可以使用变量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; 
}