I am trying to replace phrases in a text, but I tried to run this c++ program, but this deletes all the string after the replaced one, so I can't continue replacing different texts using this function. for example: input is hellookyou and the output is hellohello. the "you" part is missing. could you please explain why it is missing and what I should do. Thanks in advance
//edited this header part, and altered some of the code so that it is buildable #include <iostream> #include <conio.h>// for getch() function std::string replaceOK(std::string a){ char ok[] = "ok"; while(a.find(ok, 0) < a.length()){ a.replace(a.find(ok, 0), a.length() - a.find(ok, 3),"hello"); } return a; } int main(){ std::string a; std::cin >> a; a = replaceOK(a); std::cout << a << std::endl; return 0; } Fixed code. This won't work if it has the same phrase that I want to change in the resulting changed phrase. It will loop on endlessly.
#include <iostream> #include <conio.h>// for getch() function std::string replaceOK(std::string a){ char ok[] = "ok"; while(a.find(ok, 0) < a.length()){ std::cout << "1"; // for visualization of the loop. a.replace(a.find(ok, 0), a.length() - a.find(ok, 3),"ok1"); // changed "hello" to "ok1" } return a; } int main(){ std::string a; std::cin >> a; a = replaceOK(a); std::cout << a << std::endl; return 0; }
replaceOKreturns?a.length() - a.find(ok, 3)what is it intended to do? Why not the constant 2?