0

I'm reading this string

string input = "Hello, my name is \t Peter \n how are you ? ";

I'm printing this in my file:

Hello, my name is      Peter
how are you? 

I want the result to be:

Hello, my name is \t Peter \n how are you ? 

How can I escape special characters like tabs and break lines when writing into a file text ?

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104

2 Answers2

1
string input = "Hello, my name is \t Peter \n how are you ? ";
input = input.Replace("\n","\\n");

You can do the same for others like \t, ...

What character escape sequences are available?

Live Demo

Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171
0

Another option is to treat your string as a literal string by prepending the @ character. (https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/verbatim)

For example:

string s = @"Hello, my name is \t Peter \n how are you ? ";
Console.WriteLine(s);

Will give you the result you are looking for. However note this only works when you have the actual string text between quote marks and will not work with variables.

Also take a look at this question and its answers: Can I convert a C# string value to an escaped string literal

Alfredo MS
  • 605
  • 6
  • 8