Thursday, November 16, 2006

Find And Replace in C++

I was searching for an easiest way to find and replace in c++. This works amazing ..

Try..

std::string s = " dhanesh is not great ";

string s_toreplace = "not";

string s_replace = "very";

cout<<s<<std::endl;

std::string::size_type idx = -1;

while((idx = s.find(s_toreplace, idx+1)) != std::string::npos)

s.replace(idx, strlen(s_toreplace.c_str()), s_replace);

cout<<s<<std::endl;


1 comment:

Anonymous said...

Hi Dhanesh,

don't know if you are interested in it, but I found some mistakes in your Code. Imagine the following source text

"notDhanesh is not great"

you will find out, that the first "not" won't be replaced.

Furthermore, imagine your s_replace contains s_toreplace again and you will see that this part of s_replace will replaced again and again and ...

My solution is something like this:

wstring::size_type nStart = 0;
while ( ( nStart = sOriginal.find(sSearch, nStart) ) != wstring::npos )
{
sOriginal.replace(nStart, sSearch.size(), sReplace);
nStart += sReplace.length();
}


Greets Joe