LPCWSTR查找并替换为转义字符

时间:2019-05-31 00:52:56

标签: c++

我试图弄清楚如何查找和替换字符串(包含转义字符“ \”)。我似乎无法正常工作,我总是缺少转义字符。

我尝试将字符串更改为原义字符串,但这对我不起作用。


LPCWSTR ext1 = _wcslwr(ObjectAttributes->ObjectName->Buffer);

LPCWSTR ext2 = L"c:\\users\\vm1\\documents"; 

LPCWSTR ext3 = L"c:\\users\\vm1\\desktop";

wstring ext4 = Replace(ext1, ext2, ext3);

变量“ _wcslwr(ObjectAttributes-> ObjectName-> Buffer)”等于L“ \ ?? \ c:\ users \ vm1 \ documents \ temp22.txt”。

我一直在获取下面的Replace函数的结果字符串,使其等于“ \ ?? \ c:\ users \ vm1 \ desktopp22.txt”。结果应为“ \ ?? \ c:\ users \ vm1 \ desktop \ temp22.txt”。为什么要去除“ \ tem”部分?我认为这是由于“ \”实际上算作一个字符而不是(2)个字符。

被调用的函数在下面;


wstring Replace(const wstring& orig, const wstring& fnd, const wstring& repl)
{
    wstring ret = orig;
    size_t pos = 0;
    while (true)
    {
        pos = ret.find(fnd, pos);
        if (pos == wstring::npos)  // no more instances found
            break;
        ret.replace(pos, pos + fnd.size(), repl);  // replace old string with new string
        pos += repl.size();
    }
    return ret;
}

我希望上面的“替换”功能的输出为

"\\??\\c:\\users\\vm1\\desktop\\temp22.txt"

您如何进行这种查找和替换?

1 个答案:

答案 0 :(得分:0)

这与转义字符无关,转义字符实际上不是字符串的一部分,而仅出现在源代码中。问题是您对std::wstring::replace的争论。

您的界限就像您正在使用const_iterator, const_iterator重载,但实际上您正在使用start, length重载。那不是start, end

所以:

ret.replace(pos, fnd.size(), repl);

即删除pos +

live demo

您替换的pos(4)个字符超出了您的预期。

是的,不幸的是,字符串库中充满了像这样的小点跳动点。