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

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

    I'm currently using this function (based on other answers) in VB.NET:

    Private Shared Function SplitLines(text As String) As String()
        Return text.Split({Environment.NewLine, vbCrLf, vbLf}, StringSplitOptions.None)
    End Function
    

    It tries to split on the platform-local newline first, and then falls back to each possible newline.

    I've only needed this inside one class so far. If that changes, I will probably make this Public and move it to a utility class, and maybe even make it an extension method.

    Here's how to join the lines back up, for good measure:

    Private Shared Function JoinLines(lines As IEnumerable(Of String)) As String
        Return String.Join(Environment.NewLine, lines)
    End Function
    

提交回复
热议问题