thanks for any help in advance and apologies if this is a double post, but I read through a few other questions and I didn't find the answer I was looking for.
I am working on a project where I have to input a string (String1) and then find a specific string (String2) within String1. Then I have to replace String2 with a new string (String3).
Hope that makes sense. Anyways, I am able to achieve the desired result, but it is situational. On to the code and I'll explain on the way.
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; } I am supposed to input the following: "He lived in this small town for a long time. He graduated in 1950."
And then I am supposed to replace all instances of "He" with "She".
When I attempt this I get the following error:
terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::replace
Abort (core dumped)
However, if I enter something like.
String1 = "He He"
String2 = "He"
String3 = "She"
It will output:
"She She"