Split text with '\r\n'

前端 未结 8 428
予麋鹿
予麋鹿 2020-12-28 12:42

I was following this article

And I came up with this code:

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

using (StreamReader sr = new StreamReader(FileNam         


        
8条回答
  •  既然无缘
    2020-12-28 13:03

    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", ""));
    

提交回复
热议问题