C++ Help. String manipulation. Using string functions in C++, write the body of
ID: 3875611 • Letter: C
Question
C++ Help. String manipulation.
Using string functions in C++, write the body of the function replace_2nd, which is intended to change the string s1, replacing the 2nd occurrence of the string olds with the string news. You may add any statements you like but you may not change the function declaration in any way. You may not add parameters, subtract parameters, or change the type of any parameter.
Write 3 additional test cases, similar to the ones in the main function. You should test different things than what is already there. Your tests must compile and your function replace_2nd should also pass them.
Could use some help mostly on the first part. I feel as the program requires string manipulation such as using erase and replace, but I am unsure how to do that, help would be nice.
Original replace olds with news Final Hello jello Hello jello lo Hello jelloe Helzo jello Hello jelp Hello jaaaalloExplanation / Answer
#include<iostream>
#include<string>
using namespace std;
void replace_2nd(string &s, string olds, string news)
{
int index = s.find(olds,s.find(olds)+1); // Finding index of second occurrence of "olds" string in string s
// e.g. s = "Hello jello" , olds = "l" , news = "z" Hence index = 3
s.erase(index,olds.length()); // Erasing second occurrence of "olds" string from string s
// s = "Helo jello"
s.insert(index,news); // Adding "news" in place of "olds" string
// s = "Helzo jello"
}
void check_replace_2nd(const string &s, const string &s2, const string &s3, const string &s4)
{
string s1 = s;
replace_2nd(s1,s2,s3);
cout<<((s1==s4)?"Passed":s1)<<endl;
}
int main()
{
check_replace_2nd("Hello jello","l","z","Helzo jello");
check_replace_2nd("Hello jello","lo","p","Hello jelp");
check_replace_2nd("Hello jello","e","aaaa","Hello jaaaallo");
// New test cases
check_replace_2nd("Hey there","e","i","Hey thire");
check_replace_2nd("Please eat something","ea","pizza","Please pizzat something");
check_replace_2nd("aaaaa","aa","pp","appaa");
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.