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

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

    To split on a string you need to use the overload that takes an array of strings:

    string[] lines = theText.Split(
        new[] { Environment.NewLine },
        StringSplitOptions.None
    );
    

    Edit:
    If you want to handle different types of line breaks in a text, you can use the ability to match more than one string. This will correctly split on either type of line break, and preserve empty lines and spacing in the text:

    string[] lines = theText.Split(
        new[] { "\r\n", "\r", "\n" },
        StringSplitOptions.None
    );
    

提交回复
热议问题