C++ str_replace function


PHP offers some decent string manipulation functions including str_replace. The C++ String class also offers a replace function, but you have to pass in manual character positions found with find() when it should not require the extra step. Also, for those with a php background it is intuitive to have the same function name with the same parameters. It is also critical for such a function to operate in one pass, and for memory performance reasons for the parameters to be passed by reference.

The while loop may look a bit cryptic, but what it does is counts from the current position in 'subject' the number of characters that match the 'search' string. If the number that match is the same length as the 'search' string we have a complete match, and need to copy the 'replace' string into our new buffer.
#include <iostream>
#include <string>
 
using namespace std;
 
string& str_replace(const string &search, const string &replace, string &subject);
 
int main(int argc, char *argv[])
{
    string str;
 
    //test basic replace
    str    ="I have a lovely bunch of cocoa nuts";
    cout << str << endl;
    cout << str_replace(" ", " ;", str) << endl;
 
    //test removal of spaces
    str    ="I have a lovely bunch of cocoa nuts";
    cout << str << endl;
    cout << str_replace(" ", "", str) << endl;
 
    //this test will generate an infinite loop if not done in 1 pass
    str    ="I have a lovely bunch of cocoa nuts";
    cout << str << endl;
    cout << str_replace(" ", " a", str) << endl;
 
    return 0;
}
 
string& str_replace(const string &search, const string &replace, string &subject)
{
    string buffer;
 
    int sealeng = search.length();
    int strleng = subject.length();
 
    if (sealeng==0)
        return subject;//no change
 
    for(int i=0, j=0; i<strleng; j=0 )
    {
        while (i+j<strleng && j<sealeng && subject[i+j]==search[j])
            j++;
        if (j==sealeng)//found 'search'
        {
            buffer.append(replace);
            i+=sealeng;
        }
        else
        {
            buffer.append( &subject[i++], 1);
        }
    }
    subject = buffer;
    return subject;
}

One thing the php str_replace function does, that this function does not is accept parameters other than strings. The php str_replace function also takes an array of strings. This may make your code a bit cleaner, but functionality-wise it can be replicated simply by calling the above str_replace function multiple times.
code snippets are licensed under Creative Commons CC-By-SA 3.0 (unless otherwise specified)

Yrix on 2009-04-24 16:02:04
This function do his job with std::cout, but with ofstream (to generate a file) it doesn't work.

Nocare on 2010-08-23 14:56:48
Served my ofstream purposes perfectly, not sure what your issue with it was.

ofstream file;
file.open("shitlist2.txt");

;
string line;
ifstream ofile ("shitlist.txt");
if (ofile.is_open()){
while (!ofile.eof()){
getline(ofile,line);
line=str_replace(" ","n",line);
file

Unf on 2010-12-12 21:50:20
Well , it really replaces correctly , but speed is 70 times worth than php's str_replace.
I tried to do my own str_replace. Its working 1.5 times faster than php's str_replace and 100 times faster than your's. I can send you a copy.

pw on 2013-01-09 17:25:11
there is a replace function for this (not the member of string)

have a look at http://stackoverflow.com/questions/2896600/how-to-replace-all-occurrences-of-a-character-in-string