• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 234
  • Last Modified:

String Replacer

I am trying to write a program that will replace the word he in a string with she or he this is my code soo far and I am stuck on if I am going in the right direction or not... or what I should do from here if I am going in the right direction:

#include <iostream>
using namespace std;

string::size_type = unsigned int u[npos]
string str1 = "school";
      if (pos==npos)
void replace(string&stmt, string source, string test)

int main (){
cin >> getline.stmt;
replace (stmt, "he", "she or he");
replace (stmt, "him", "her or him");
replace (stmt, "his", "her(s) or his");

start loop
2 Solutions
I suggest you try to solve simpler problems first and gradually work your way up to this one.  For example, first make a program that can read in a string.  Then improve it so it can find a specified string in an input string.  Then improve it so it can find all occurrences of a specified string in the input string.  Finally, make it do replacements.  Get it to compile and test it after each step before going on the next one.
>>>> string::size_type = unsigned int u[npos]


>>>> string::size_type

??? There is no need to play with basic_string::size_type

>>>> pos=str1.find("he")
>>>> pos=str1.find("him")

The second statement overwrites the value of pos ???

>>>> void replace(string&stmt, string source, string test)

There is already a std::string::replace and I don't think it is a good idea to have a global function of the same name but with different arguments. Better use a different name and return the new string by value (rather than passing a writeable string variable).

string replaceString(const string& text, const string& strold, const string& strnew);

If the function should replace all occurences of the old string found you should name it 'replaceAllString' to make that clear.

For implementation you need to call the string::find (if replacing all occurences, call it in a loop). Then use the pos returned as first argument to string::replace. The second argument is the length of the string you want to replace. The thirs argument is the string you want take for replace.

Note, you need to check the return of 'find' not equal to string::npos or break. If replacing all occurences you need to increment the position returned by find by the length of the new string before continuing the loop.

>>>> start loop

That function is not needed.

Regards, Alex


Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now