Question

I have the following code:

string test = @"1
2
3";

This line:

Console.WriteLine(test.Replace("\n", "")); //3

prints "3", instead of "123", which is what I expected. Why does this method return only the last line of my string, and how can I otherwise remove all new-lines?

Était-ce utile?

La solution

Console.WriteLine(test.Replace("\n", "")); returns all numbers for me. When dealing with linebreaks you must be aware that newline may be \r\n, it depends on platform. In this case you should use this:

test.Replace("\r\n", "")
// or better:
test.Replace(Environment.NewLine, "")

Refrer to Difference between “\n” and Environment.NewLine

Autres conseils

On the off-chance that the newline might differ between the system on which you compose the text file and the system on which it is compiled or run, you might want to do

string test = @"1
2
3";
Console.WriteLine(test.Replace(@"
", "");

to do your best to ensure that the newline in your string literal is the same as the newline you're replacing.

A verbatim string uses the line endings of the source code file it is in. Given that source control environments like git may convert line endings to the native line ending the string

string test = @"1
2
3";

could have any set of line endings ("\r\n","\r", or "\n"). The only safe way to remove any of those possible ones is:

Console.WriteLine(test.Replace("\n", "").Replace("\r", ""));

This makes no assumptions about the two code snippets being in the same source file (since two source files don't have to have the same line endings).

The verbatim string is using "\r\n" as the line break, so the result of your replace is "1\r2\r3".

If you instead use test.Replace("\r\n", "") it will work as expected. To handle the case of any number of \r or \n use: test.Replace("\r", "").Replace("\n", ""). That will work for \r, \n, or \r\n as a separator.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top