Easiest way to split a string on newlines in .NET?

后端 未结 16 2477
抹茶落季
抹茶落季 2020-11-22 06:57

I need to split a string into newlines in .NET and the only way I know of to split strings is with the Split method. However that will not allow me to (easily) split on a ne

16条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 07:46

    For a string variable s:

    s.Split(new string[]{Environment.NewLine},StringSplitOptions.None)
    

    This uses your environment's definition of line endings. On Windows, line endings are CR-LF (carriage return, line feed) or in C#'s escape characters \r\n.

    This is a reliable solution, because if you recombine the lines with String.Join, this equals your original string:

    var lines = s.Split(new string[]{Environment.NewLine},StringSplitOptions.None);
    var reconstituted = String.Join(Environment.NewLine,lines);
    Debug.Assert(s==reconstituted);
    

    What not to do:

    • Use StringSplitOptions.RemoveEmptyEntries, because this will break markup such as Markdown where empty lines have syntactic purpose.
    • Split on separator new char[]{Environment.NewLine}, because on Windows this will create one empty string element for each new line.

提交回复
热议问题