0

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" )

5

2 Answers 2

3
size_t position = 0; while((position = sentence.find(replacedString, position)) != sentence.npos) { sentence.replace(position, strLength, stringToReplace); position += stringToReplace.length(); } 

Try the piece of code though I did not get a chance to test it.

Sign up to request clarification or add additional context in comments.

2 Comments

While I'm sure this probably works, I would have to look at it as I'm not familiar with items such as size_t. But if you care to break it down, I'm all ears.
You can regard size_t as unsigned int - usually when we operate on size or index, size_t is used. In the loop, we find the old string from the current position using sentence.find(replacedString, position). If not found, it will return sentence.npos to end the loop. If found, it will return the starting index of that old string so that we can replace it with new string. After the substitution, we move to next possible index for old string - that's why "position += stringToReplace.length()".
2

Replacing parts of a string and inserting a new string can be accomplished with a while loop (to continuously find a string until we run out of spots we find the string).

EDIT: This method did not use the string::replace method. Check out @Dong Li's answer for the replace method. However, the code at the bottom is code that works for string::erase and string::insert method.

Here is the code to accomplish this task:

#include <iostream> using namespace std; int main() { string replacedString("that"); string stringToReplace("the"); string sentence("the dog jumped over the fence"); //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; } 

The code outputs:

that dog jumped over that fence 

Explanation

We first start by initially trying to find the string:

int pos = sentence.find(stringToReplace); 

If we do, then pos will equal to the position where the first occurance is located in.

Next, a while loop will be used to check if the string exists (it doesn't exist if it returns string::npos)

while(pos != string::npos) 

Now, after we found out that the string does exist, we will take the targeted string at position pos and delete it:

sentence.erase(pos,stringToReplace.length()); 

And, finally, insert the new string at position pos:

sentence.insert(pos,replacedString); 

Then, we continue repeating finding the string in

pos = sentence.find(stringToReplace); 

until we have no remaning targeted strings.

3 Comments

May I ask what the following means: string::npos ... I'm not familiar with the :: or the word npos
cplusplus.com/reference/string/string/npos It's just equal -1, which means the string doesn't exist.
@kiddsupreme: You probably want to use std::string::replace instead of doing erase followed by insert. Look at some of the duplicate questions in the comments above.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.