c++ - Replace all occurrences of one string with another in a stream of text -


as title says, how replace string string? example: user enter 3 inputs. first input string program replace; second string replace input1; , third string printed out. if:

input1 = peanut

input2 = coconut

input3 = replacepeanutreplace

output: replacecoconutreplace

i have started program can replace words same length. tried searching problem, not understand given solutions since new @ c/c++.

char replacing[100]; char replacement[100]; char original[1000]; int count;  cin >> replacing; cin >> replacement;  while(! cin.eof()) {     cin >> original;      char * pch;       pch = strstr (original, replacing);      count = strlen(replacement);     strncpy (pch, replacement, count);       cout << original << endl;  } 

what about:

  • you first find (if any) occurrence of string
  • use replace substitute occurrence second string

here should work:

    bool replacefirst(string& input, const std::string& tobereplaced, const std::string& replacement) {     size_t start_pos = input.find(tobereplaced);     if(start_pos == std::string::npos)         return false; //substring not found!       input.replace(start_pos, tobereplaced.length(), replacement); //found. can replace!     return true; } 

since using array of char instead of string have make sure replacing not lead out of bound (strings auto-resize you).


Comments

Popular posts from this blog

html - How to set bootstrap input responsive width? -

javascript - Highchart x and y axes data from json -

javascript - Get js console.log as python variable in QWebView pyqt -