简体   繁体   中英

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 required string. 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 .

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;    
}
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).

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM