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


当前回答

使用StringReader怎么样?

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

其他回答

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

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

//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]);
}

愚蠢的回答:写到一个临时文件,这样你就可以使用可敬的 文件。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;
    }

尽量避免使用字符串。分割是一种通用的解决方案,因为在使用函数的任何地方都会使用更多的内存——原始字符串和分割副本,都在内存中。相信我,当你开始扩展时,这可能是一个非常严重的问题——运行一个32位的批处理应用程序处理100MB的文档,你会在8个并发线程时崩溃。并不是说我以前去过那里……

相反,使用这样的迭代器;

public static IEnumerable<string> SplitToLines(this string input)
{
    if (input == null)
    {
        yield break;
    }

    using (System.IO.StringReader reader = new System.IO.StringReader(input))
    {
        string line;
        while ((line = reader.ReadLine()) != null)
        {
            yield return line;
        }
    }
}

这将允许你在你的数据周围做一个更有效的内存循环;

foreach(var line in document.SplitToLines()) 
{
    // one line at a time...
}

当然,如果你想把它都放在内存中,你可以这样做;

var allTheLines = document.SplitToLines().ToArray();