usando una variable para la cadena de formato en String.Format, cuando incluye \n

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:

Hola Steve

Welcome to the programme

¿Alguna idea?

preguntado el 28 de mayo de 14 a las 14:05

haría .Replace("\n", Environment.NewLine) ¿trabajo? -

Debieran ser .Replace("\\n", Environment.NewLine) -

@Complexity that doesn't work. -

thanks @Stijn and amnezjak - that was the right direction to go. -

2 Respuestas

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.

contestado el 23 de mayo de 17 a las 13:05

Vuelva a colocar la \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);

contestado el 28 de mayo de 14 a las 14:05

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.