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


当前回答

其实很简单。

VB。NET:

Private Function SplitOnNewLine(input as String) As String
    Return input.Split(Environment.NewLine)
End Function

C#:

string splitOnNewLine(string input)
{
    return input.split(environment.newline);
}

其他回答

根据Guffa的答案,在扩展类中使用:

public static string[] Lines(this string source) {
    return source.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
}
using System.IO;

string textToSplit;

if (textToSplit != null)
{
    List<string> lines = new List<string>();
    using (StringReader reader = new StringReader(textToSplit))
    {
        for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
        {
            lines.Add(line);
        }
    }
}

我不知道环境。换行,但我想这是一个很好的解决方案。

我的尝试是:

        string str = "Test Me\r\nTest Me\nTest Me";
        var splitted = str.Split('\n').Select(s => s.Trim()).ToArray();

额外的. trim删除了任何可能仍然存在的\r或\n(例如在windows上,但是用os x换行符分隔字符串)。可能不是最快的方法。

编辑:

正如注释所正确指出的那样,这也会删除行开头或新换行之前的任何空白。如果需要保留空白,请使用其他选项之一。

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

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

好吧,实际上拆分应该做:

//Constructing string...
StringBuilder sb = new StringBuilder();
sb.AppendLine("first line");
sb.AppendLine("second line");
sb.AppendLine("third line");
string s = sb.ToString();
Console.WriteLine(s);

//Splitting multiline string into separate lines
string[] splitted = s.Split(new string[] {System.Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries);

// Output (separate lines)
for( int i = 0; i < splitted.Count(); i++ )
{
    Console.WriteLine("{0}: {1}", i, splitted[i]);
}