如何在C ++字符串中用“ \”替换“ \”

sta*_*ck_ 0 c++ visual-c++ c++11

我有string My_string = "First string\r\nSecond string\r\nThird string"...等等。新字符串从\ r \ n之后开始,我想替换\\\

我已经尝试过:- My_string.replace("\","\\");但这对我不起作用。还有其他方法吗?

Ale*_*agh 5

如果要将转义字符(\ n,\ r等)转换为文字反斜杠和[az]字符,则可以使用switch语句并将其追加到缓冲区。假设使用C ++标准库字符串,则可以执行以下操作:

std::string escaped(const std::string& input)
{
    std::string output;
    output.reserve(input.size());
    for (const char c: input) {
        switch (c) {
            case '\a':  output += "\\a";        break;
            case '\b':  output += "\\b";        break;
            case '\f':  output += "\\f";        break;
            case '\n':  output += "\\n";        break;
            case '\r':  output += "\\r";        break;
            case '\t':  output += "\\t";        break;
            case '\v':  output += "\\v";        break;
            default:    output += c;            break;
        }
    }

    return output;
}
Run Code Online (Sandbox Code Playgroud)

这使用switch语句,并将所有常见的转义序列转换为文字'\',并使用表示转义序列的字符。所有其他字符均原样追加到字符串中。简单,高效,易于使用。