[英]C++ Find/Replace Strings
感謝您的事先幫助和歉意,如果這是重復的帖子,但是我通讀了其他一些問題,但沒有找到我想要的答案。
我正在一個項目中,我必須輸入一個字符串(String1),然后在String1中找到一個特定的字符串(String2)。 然后,我必須用新的字符串(String3)替換String2。
希望有道理。 無論如何,我都能達到預期的效果,但這是視情況而定。 在代碼上,我將在后面解釋。
int main()
{
string string1, from, to, newString;
cout << "Enter string 1: ";
getline(cin, string1);
cout << "Enter string 2: ";
cin >> from;
cout << "Enter string 3: ";
cin >> to;
newString = replaceSubstring(string1, from, to);
cout << "\n" << newString;
}
string replaceSubstring(string string1, string from, string to)
{
int index, n, x = 0;
n = from.length();
while (x < string1.length() - 1)
{
index = string1.find(from, x);
string1.replace(index, n, to);
x = index + to.length() - 1;
}
return string1;
}
我應該輸入以下內容:“他在這個小鎮上住了很長時間。他於1950年畢業。”
然后我應該用“她”替換所有“他”的實例。
當我嘗試這樣做時,出現以下錯誤:
拋出'std :: out_of_range'實例后調用終止
what():basic_string :: replace
中止(核心棄權)
但是,如果我輸入類似的內容。
String1 =“何和”
String2 =“他”
String3 =“她”
它將輸出:
“她她”
當您的FIND
呼叫失敗時,您將在此區域使用錯誤的index
:
index = string1.find(string2, x);
string1.replace(index, n, string3);
在將index
傳遞到Replace
之前檢查index
的值
首先,如果函數將原始字符串更改為“ in place”會更好。 在這種情況下,它將看起來像泛型函數替換,類似於成員函數替換。
通話后請檢查是否索引
index = string1.find(string2, x);
等於std::string::npos
。 否則,該函數將引發異常。
另外這句話
x = index + to.length() - 1;
是錯的
它看起來像
x = index + to.length();
例如,假設您具有值為"a"
字符串,並希望將其替換為"ba"
。 在這種情況下,如果使用您的語句,x將等於1(x = 0 + 2-1)。 並指向“ ba”中的“ a”。 然后函數再次將“ a”替換為“ ba”,您將得到“ bba”,依此類推。 那就是循環將是無限的。
我將通過以下方式編寫函數
#include <iostream>
#include <string>
void replace_all( std::string &s1, const std::string &s2, const std::string &s3 )
{
for ( std::string::size_type pos = 0;
( pos = s1.find( s2, pos ) ) != std::string::npos;
pos += s3.size() )
{
s1.replace( pos, s2.size(), s3 );
}
}
int main()
{
std::string s1( "Hello world, world, world" );
std::string s2( "world" );
std::string s3( "mccdlibby" );
std::cout << s1 << std::endl;
replace_all( s1, s2, s3 );
std::cout << s1 << std::endl;
return 0;
}
輸出是
Hello world, world, world
Hello mccdlibby, mccdlibby, mccdlibby
Find函數返回string x
的起始索引,索引從0 to len-1
而不是1 to len
。
int idx = string1.find(string2, x);
if(idx >= 0)
string1.replace(index, n, string3);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.