Replace com does not work

Asked

Viewed 1,680 times

1

I’m trying to make a Replace() but it doesn’t work. I need to change \ for \\.

"\r\n".Replace(@"\", "\\");

he just returns me : "\r\n" and not "\\r\\n".

1 answer

1


First of all, I don’t think you need to do this, but I’m just speculating. I think there’s another problem that’s giving you a wrong solution.

It’s not working because it’s changing something for itself. @"\" is exactly the same thing as "\\".

That’s how it works:

var texto = @"\r\n".Replace(@"\", @"\\");

The @ causes the escape character \ be considered a normal character, among other things. When you use \\ without the @ the backslash is an escape and when you use two backslash means you should consider the bar as normal character.

Do not forget to store the information somewhere (as I did) or immediately use in the expression.

using static System.Console;

public class Program {
    public static void Main() {
        var texto = @"É necessário Cadastrar o(s) seguinte(s) Parâmetro(s):SENHA_FTP\r\n";
        WriteLine(texto.Replace(@"\", @"\\"));
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

  • didn’t work out...

  • I’d forgotten a @, now yes.

  • Your example worked, but with my non... text="You need to Register the following(s) Parameter(s):SENHA_FTP r n" text = @text. Replace(@"", @"\");

  • It worked your example, I did what you put in the question. If what you wanted to do was something else, you should have asked the question what you wanted.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.