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

问题描述:

我需要在 .NET 中将字符串拆分为换行符,我知道的唯一拆分字符串的方法是使用 Split 方法.但是,这不允许我(轻松)在换行符上拆分,那么最好的方法是什么?

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 newline, so what is the best way to do it?

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

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
);