1

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?

1
  • 2
    If this is purely a learning exercise, great, but otherwise, why aren't you using std::string::replace? Commented May 28, 2013 at 10:38

2 Answers 2

2
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();
    }       
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.