0

I would like to read a line from a file, and use that line as the format specifier for a string.

The line in the file contains a newline character escape sequence \n. so it may look like this:

Hello{0}\n\nWelcome to the programme

And I want to use it in a situation like this:

string name_var = "Steve";    
string line = ReadLineFromFile();
string formatted_line = String.Format(line, name_var);

Unfortunately, the result looks like:

Hi Steve\n\nWelcome to the programme

Whereas I'd like it to look like:

Hi Steve

Welcome to the programme

Any ideas?

Marcin
  • 1,889
  • 2
  • 16
  • 20

2 Answers2

4

When you use escape sequences such as \n in your C# program, the compiler processes the string, and inserts the code of the corresponding non-printable character into the string literal for you.

When you read a line from a file or from another import source, processing of escape sequences becomes your program's responsibility. There is no built-in way of doing it. If all you want is \n, you could use a simplistic

formatString = formatString.Replace("\\n", "\n");

If you would like to support other escape sequences, such as ones for UNICODE characters, you could use solutions from answers to this question.

Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

Replace the \n in your string with the newline specifier like this:

string name_var = "Steve"; 

string line = ReadLineFromFile();
line = line.Replace("\\n", Environment.NewLine);

string formatted_line = String.Format(line, name_var);
DavidG
  • 113,891
  • 12
  • 217
  • 223