字符串替换中的c++错误

C++ error in string replace

本文关键字:c++ 错误 替换 字符串      更新时间:2023-10-16

我创建了一个函数来替换字符串。

它看起来像这样:

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

但是,如果我的字符串size==1,并且"what"正是该字符串,它将不会替换它。

例如

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

…不能替换"-"

我不知道我哪里错了。

有谁能帮忙吗?
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();
    }       
}

函数的主要部分工作正常。问题在于if (!temp.empty())部分,它完全没有意义。用

一行替换整个if块
src = temp + wstring(src.begin() + prev_pos, src.end());

,它应该可以正常工作。

提示:尽量用文字解释函数的最后一部分是做什么的