且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 .NET 中用换行符拆分字符串的最简单方法?

更新时间:2023-11-28 21:24:34

要拆分字符串,您需要使用采用字符串数组的重载:

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

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


如果要处理文本中不同类型的换行符,可以使用匹配多个字符串的功能.这将在任一类型的换行符上正确拆分,并在文本中保留空行和间距:


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 string[] { "
", "
", "
" },
    StringSplitOptions.None
);