I've been trying to search for an answer to this question, but I haven't had any luck so far. I'm in a class learning C++. The exercise is to look for the occurrence of a word in a string and replace it with another word. I know I probably need some sort of loop to iterate through the entire string, but I'm not sure how to do that. At the moment, my program finds the first occurrence in the string and replaces it. However there is a second occurrence of the word that the program currently does not find and replace. Please take a look at what I have so far:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string replacedString("that");
string stringToReplace("the");
string sentence("the dog jumped over the fence");
int strLength = stringToReplace.length();
int position = sentence.find(stringToReplace);
sentence.replace(position, strLength, replacedString);
cout << sentence;
return 0;
}
Okay, thanks Patrick for helping me understand how strings work. I went ahead and made some changes to my code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string sentence; // String to hold the user inputted phrase
string stringToReplace; // String to hold the user inputted string that will be replaced
string replacedString; // String to hold the user inputted replacement string
cout << "Please type in a sentence: " << endl;
getline(cin, sentence);
cout << "Please type in a string to search for: " << endl;
getline(cin, stringToReplace);
cout << "Please type in a replacement string: " << endl;
getline(cin, replacedString);
//First time, we will see if we find the string
int pos = sentence.find(stringToReplace);
while (pos != string::npos)
{
//Erase the targeted string at the location we set
sentence.erase(pos, stringToReplace.length());
//Insert the new string where we last deleted the old string
sentence.insert(pos, replacedString);
//Get position of targeted string to erase
pos = sentence.find(stringToReplace);
}
cout << sentence << '\n';
return 0;
}
Would there be a way to add in a message if the searched string wasn't found in the sentence -- Something along the lines of, If not found, (cout << "Not Found" )