[英]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.