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

后端 未结 16 2316
抹茶落季
抹茶落季 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:34

    I did not know about Environment.Newline, but I guess this is a very good solution.

    My try would have been:

            string str = "Test Me\r\nTest Me\nTest Me";
            var splitted = str.Split('\n').Select(s => s.Trim()).ToArray();
    

    The additional .Trim removes any \r or \n that might be still present (e. g. when on windows but splitting a string with os x newline characters). Probably not the fastest method though.

    EDIT:

    As the comments correctly pointed out, this also removes any whitespace at the start of the line or before the new line feed. If you need to preserve that whitespace, use one of the other options.

提交回复
热议问题