Reputation: 23
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;
}
Upvotes: 0
Views: 75
Reputation: 62
The problem lies in the way you are using the a.replace()
function.
The replace()
function works in the way
a.replace(0,3,"red")
This would change 3 characters from the 0th index and replace them with the string "red".
So in you case you are going to the index where you encounter the first occurence of "ok" string using a.find("ok",0)
, then by using a.length()-a.find("ok",3)
, you are getting 5 as the value and replacing them with "hello".
So you are basically doing a.replace(5,5,"hello")
. Because of this the "okyou" part gets replaced by "hello" string.
The code is here:
#include <iostream>
#include <conio.h>// for getch() function
using namespace std;
string replaceOK(string a){
string ok = "ok";
int n=a.find("ok",0);
int p=1;//for counting the number of occurence of "ok"
while(n < a.length()){
if(p==1)
a.replace(n,ok.size(),"hello"); //replace 1st occurence of ok to hello
if(p==3)
a.replace(n,ok.size(),"ok1"); //replace 3rd occurence of ok to ok1
if(n+2>=a.length())
break;
n=a.find("ok",n+2);
p+=1;
}
return a;
}
int main(){
string a;
cin >> a;
a = replaceOK(a);
cout << a << std::endl;
return 0;
}
Upvotes: 1