kiddsupreme
kiddsupreme

Reputation: 115

How to loop through a string and replace parts within it? c++

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

Upvotes: 0

Views: 4174

Answers (2)

Patrick Yu
Patrick Yu

Reputation: 972

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.

Upvotes: 2

Dong Li
Dong Li

Reputation: 133

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.

Upvotes: 3

Related Questions