1

I have string My_string = "First string\r\nSecond string\r\nThird string" ... ect. New string starts after \r\n and I want to replace \ with \\.

I have tried with:- My_string.replace("\","\\"); But it doesn't work for me. Is there any another way to do it?

Eziz Durdyyev
  • 1,110
  • 2
  • 16
  • 34
stack_
  • 35
  • 2
  • 7
  • 2
    Is it C or C++? There is no string type in C. – Maku Jan 15 '18 at 10:18
  • 1
    There is no thing such as `"\"` in C or C++. It gives you the start of an escape sequence. So it isn't really clear what you are trying to do here. – Lundin Jan 15 '18 at 10:18
  • 1
    One reason for problems is because there are *no* backslashes in the string. If you have a string literal then the compiler will replace escape sequences (like `"\r\n"`) with their actual encoded values (using [ASCII](http://en.cppreference.com/w/cpp/language/ascii) the example of `"\r\n"` will be replaced by the two bytes `13` and `10` inside the string). – Some programmer dude Jan 15 '18 at 10:19
  • look at the syntax highlighting, don't you see anything suspicious? – phuclv Jan 15 '18 at 10:22
  • 1
    Voted to close as unclear. @stack_: If you can update the question with valid code and be more clear about what you want, then please do so. – Cheers and hth. - Alf Jan 15 '18 at 10:24
  • It is for c++11 string – stack_ Jan 15 '18 at 10:33

2 Answers2

5

If you want to convert escape characters (\n, \r, etc.) to a literal backslash and the [a-z] character, you can use a switch statement and append to a buffer. Assuming a C++ standard library string, you may do:

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

This uses a switch statement, and converts all common escape sequences to a literal '\' and the character used to represent the escape sequence. All other characters are appended as-is to the string. Simple, efficient, easy-to-use.

Alex Huszagh
  • 13,272
  • 3
  • 39
  • 67
-1

Try this code?

My_string.replace( My_string.begin(), My_string.end(), 'x', 'y'); //replace all occurances of 'x' with 'y'

And here is a similar question

Eziz Durdyyev
  • 1,110
  • 2
  • 16
  • 34