In: Computer Science
how to write a c++ program that replaces certain words with two "**"
input: I went to the store
To buy some fruit
Apples are red
I like oranges better
I saw grapes are green
apples are red, oranges, grapes are green (sub strings that need to be replaced)
iterate through the string input and get an output that replaces the sub strings with **
If the sub strings are not in the input just return the string as it is
Just replace what is in the string if it matches the sub string so if it says in the string I saw grapes are green and the sub string that needs replacing is grapes are green just replace grapes are green. If it just says grapes in the sentence do not replace it.
#include <iostream>
#include <string>
void findReplace(std::string & input, std::string subStr,
std::string replaceWith)
{
// Get the first occurrence of the subString
size_t firstPosition = input.find(subStr);
// Repeat using while loop till end is reached
while( firstPosition != std::string::npos)
{
// Replace the occurrence of
subString
input.replace(firstPosition,
subStr.size(), replaceWith);
// Get the next occurrence of the
string after the current position
firstPosition =input.find(subStr,
firstPosition + replaceWith.size());
}
}
int main()
{
//Initialize the string
std::string input = "I went to the store To buy some
fruit Apples are red I like oranges better I saw grapes are
green";
//Print the string
std::cout<<input<<std::endl;
//Call findReplace and replace the subString
findReplace(input, "Apples are red", "**");
findReplace(input, "oranges", "**");
findReplace(input, "grapes are green", "**");
//Print the new string
std::cout<<input<<std::endl;
return 0;
}