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

kiddsupreme
  • 115
  • 1
  • 3
  • 13
  • You need a loop. Loop condition = check if the word exists in the sentence. If it does, replace the word. – yizzlez Nov 21 '15 at 01:22
  • understood, but how would i go about setting up that loop? – kiddsupreme Nov 21 '15 at 01:46
  • You might take a look here : https://stackoverflow.com/questions/4643512/replace-substring-with-another-substring-c – coincoin Nov 21 '15 at 01:56
  • Possible duplicate of [How do I replace all instances of a string with another string?](http://stackoverflow.com/questions/5343190/how-do-i-replace-all-instances-of-a-string-with-another-string) – Blastfurnace Nov 21 '15 at 02:04
  • Here's yet another duplicate: [Replace part of a string with another string](http://stackoverflow.com/questions/3418231/replace-part-of-a-string-with-another-string) – Blastfurnace Nov 21 '15 at 02:05

2 Answers2

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.

Dong Li
  • 133
  • 6
  • 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. – kiddsupreme Nov 21 '15 at 02:43
  • 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()". – Dong Li Nov 25 '15 at 22:47
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.

Patrick Yu
  • 972
  • 1
  • 7
  • 19
  • May I ask what the following means: string::npos ... I'm not familiar with the :: or the word npos – kiddsupreme Nov 21 '15 at 02:04
  • http://www.cplusplus.com/reference/string/string/npos/ It's just equal -1, which means the string doesn't exist. – Patrick Yu Nov 21 '15 at 02:09
  • @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. – Blastfurnace Nov 21 '15 at 02:09