我需要在. net中将字符串分割为换行符,我所知道的分割字符串的唯一方法是使用split方法。然而,这将不允许我(容易)在换行上分裂,那么最好的方法是什么?


当前回答

要拆分一个字符串,你需要使用一个字符串数组的重载:

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

编辑: 如果要处理文本中不同类型的换行符,可以使用匹配多个字符串的功能。这将正确地拆分任意类型的换行,并保留文本中的空行和空格:

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

其他回答

使用StringReader怎么样?

using (System.IO.StringReader reader = new System.IO.StringReader(input)) {
    string line = reader.ReadLine();
}

要拆分一个字符串,你需要使用一个字符串数组的重载:

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

编辑: 如果要处理文本中不同类型的换行符,可以使用匹配多个字符串的功能。这将正确地拆分任意类型的换行,并保留文本中的空行和空格:

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

你应该能够很容易地分割你的字符串,就像这样:

aString.Split(Environment.NewLine.ToCharArray());

愚蠢的回答:写到一个临时文件,这样你就可以使用可敬的 文件。readline

var s = "Hello\r\nWorld";
var path = Path.GetTempFileName();
using (var writer = new StreamWriter(path))
{
    writer.Write(s);
}
var lines = File.ReadLines(path);

Regex也是一个选项:

    private string[] SplitStringByLineFeed(string inpString)
    {
        string[] locResult = Regex.Split(inpString, "[\r\n]+");
        return locResult;
    }