[c#] Split text with '\r\n'

I was following this article

And I came up with this code:

string FileName = "C:\\test.txt";

using (StreamReader sr = new StreamReader(FileName, Encoding.Default))
{
    string[] stringSeparators = new string[] { "\r\n" };
    string text = sr.ReadToEnd();
    string[] lines = text.Split(stringSeparators, StringSplitOptions.None);
    foreach (string s in lines)
    {
        Console.WriteLine(s);
    }
}

Here is the sample text:

somet interesting text\n
some text that should be in the same line\r\n
some text should be in another line

Here is the output:

somet interesting text\r\n
some text that should be in the same line\r\n
some text should be in another line\r\n

But what I want is this:

somet interesting textsome text that should be in the same line\r\n
some text should be in another line\r\n

I think I should get this result but somehow I am missing something...

This question is related to c# string split

The answer is


The problem is not with the splitting but rather with the WriteLine. A \n in a string printed with WriteLine will produce an "extra" line.

Example

var text = 
  "somet interesting text\n" +
  "some text that should be in the same line\r\n" +
  "some text should be in another line";

string[] stringSeparators = new string[] { "\r\n" };
string[] lines = text.Split(stringSeparators, StringSplitOptions.None);
Console.WriteLine("Nr. Of items in list: " + lines.Length); // 2 lines
foreach (string s in lines)
{
   Console.WriteLine(s); //But will print 3 lines in total.
}

To fix the problem remove \n before you print the string.

Console.WriteLine(s.Replace("\n", ""));

Similar questions with c# tag:

Similar questions with string tag:

Similar questions with split tag: