tmighty
tmighty

Reputation: 11399

C++ error in string replace

I have created a function that replaces a string.

It looks like this:

void replace_with(wstring& src, const wstring& what, const wstring& with)
{    
    if (what != with) {
        wstring temp;
        wstring::size_type prev_pos = 0, pos = src.find(what, 0);
        while ( wstring::npos != pos ) {
            temp += wstring(src.begin() + prev_pos, src.begin() + pos) + with;
            prev_pos = pos + what.size();
            pos = src.find(what, prev_pos);
        }
        if ( !temp.empty() ) {
            src = temp + wstring(src.begin() + prev_pos, src.end());
            if (wstring::npos == with.find(what)) {
                replace_with(src, what, with);
            }
        }
    }
}

However, if my string is size==1, and the "what" is exactely the string, it will not replace it.

For example

wstring sThis=L"-";
replace_with(sThis,L"-",L"");

... will not replace the "-".

I don't see where I went wrong.

Can anybody help, please?

Upvotes: 1

Views: 138

Answers (2)

Andrey Volk
Andrey Volk

Reputation: 3549

void replace_with(wstring &src, wstring &what, wstring &with) {
    for (size_t index = 0; ( index = src.find(what, index) ) != wstring::npos ; ) {
        src.replace(index, what.length(), with);
        index += with.length();
    }       
}

Upvotes: 2

Sebastian Redl
Sebastian Redl

Reputation: 71919

The main part of the function is working fine. The problem is the if (!temp.empty()) part, which makes absolutely no sense. Replace the entire if block with just the line

src = temp + wstring(src.begin() + prev_pos, src.end());

and it should work fine.

Hint: try to explain in words what the last part of the function is doing.

Upvotes: 1

Related Questions