How to show Escape sequences as String in C#?

Asked

Viewed 39 times

-1

I have a C# method that takes a String and sometimes has output escapes inside, like \n. It does its function normally, which is to skip the line. But I want them to be shown as String.

How can I do that?

I tried to remove the escapes with String.Remove and add \\n in the same position with String.Insert, so that he would imprint a string showing the escape, but did not succeed.

public class Program
{
  public static void Main()
  {
    String name = "N ffns bt,\nYr wrtng";
    Console.WriteLine(name);
  }
}

/* 
Saída:
"N ffns bt,
Yr wrtng" 
*/

Exit I want to get:

"N ffns bt,\nYr wrtng"
  • 1

    I edited, I want to be shown the escapes when I, for example, perform Console.WriteLine.

  • 1

    Console.WriteLine(name.Replace("\n", "\\n"))??? that’s it

  • 1

    string name = @"N ffns bt,\nYr wrtng" the @ will store the string literally... your problem is exactly this or getting another variable?

  • @Leandroangelo, can you use in Return? I’m receiving another variable and returning.

  • @Ricardopunctual, It works until the moment I return it from a function, because there the result of the function is N ffns bt,\\nYr wrtng, two-bar

  • @Eduardonogueira "This works until the moment I return it from a function" more is something you need to solve :) according to your example, the Replace works perfectly, now if it’s a different case of the question, need to edit the question then or adapt the solution

Show 1 more comment

1 answer

0

string stg = @"N ffns bt,\nYr wrtng";
Console.WriteLine(stg);

Console output:

> N ffns bt,\nYr wrtng

Using "@" it ignores string escapes

Browser other questions tagged

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