kusur
kusur

Reputation: 618

C++ :- Replacing a piece of string by another string

I am trying to write a REPLACE function that will replace the given string by the requiredstring. When I am dry running the function on paper, everything seems to be fine but while executing, it's not giving the correct output. The code is as follows:-

string REPLACE(string src,string reqd,string given)
{
    int i,j,k;
    int pos = FIND(src,given);
    if(pos==-1)
        return "";
    else
    {
        char *arr = new char[src.length()+reqd.length()-given.length()];  // creating the array that will hold the modified string
        for(i=0;i<pos;i++)
            arr[i] = src[i];     // copying the initial part of the string
        for(i=pos,j=0;i<pos+reqd.length()+1&&j<reqd.length();i++,j++)
            arr[i] = reqd[j];    // copying the required string into array
        for(i=pos+reqd.length()+1,k=0;i<sizeof(arr);i++,k++)
            arr[i] = src[pos+given.length()+k];   // copying the remaining part of source string into the array
        return arr;
    }   
}

Here the FIND is also written by me and has been tested in many cases. I don't see any error in FIND.

Upvotes: 0

Views: 177

Answers (3)

jrok
jrok

Reputation: 55395

for(i=pos+reqd.length()+1,k=0; i<sizeof(arr); i++,k++)
//                               ^^^^^^^^^^^
//                           This is always the same

sizeof(arr) is the same as sizeof(char*), a compile-time constant value. You need to keep the size of a dynamically allocated array yourself (or, better yet, simply use std::string instead).

Upvotes: 1

Abhishek Bansal
Abhishek Bansal

Reputation: 12715

I don't think it is a good idea to mix std::string with char arrays. Following should work:

string REPLACE(string src,string reqd,string given)
{
    int pos = FIND(src,given);

    src.replace( pos, given.size(), reqd );
    return src;    
}

Upvotes: 1

sara
sara

Reputation: 3934

Assuming you do not want to re-invent the wheel:

string REPLACE(string src,string reqd,string given)
{
    string str(src);
    size_t pos = str.find(given);
    if(pos == std::string::npos)
        return "";
    str.replace(pos, given.length(), reqd);
    return str;
}

Upvotes: 0

Related Questions