Best way to split string into lines

前端 未结 10 844
情书的邮戳
情书的邮戳 2020-11-27 13:53

How do you split multi-line string into lines?

I know this way

var result = input.Split(\"\\n\\r\".ToCharArray(), StringSplitOptions.RemoveEmptyEntri         


        
10条回答
  •  北海茫月
    2020-11-27 14:26

    I had this other answer but this one, based on Jack's answer, is significantly faster might be preferred since it works asynchronously, although slightly slower.

    public static class StringExtensionMethods
    {
        public static IEnumerable GetLines(this string str, bool removeEmptyLines = false)
        {
            using (var sr = new StringReader(str))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    if (removeEmptyLines && String.IsNullOrWhiteSpace(line))
                    {
                        continue;
                    }
                    yield return line;
                }
            }
        }
    }
    

    Usage:

    input.GetLines()      // keeps empty lines
    
    input.GetLines(true)  // removes empty lines
    

    Test:

    Action measure = (Action func) =>
    {
        var start = DateTime.Now;
        for (int i = 0; i < 100000; i++)
        {
            func();
        }
        var duration = DateTime.Now - start;
        Console.WriteLine(duration);
    };
    
    var input = "";
    for (int i = 0; i < 100; i++)
    {
        input += "1 \r2\r\n3\n4\n\r5 \r\n\r\n 6\r7\r 8\r\n";
    }
    
    measure(() =>
        input.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None)
    );
    
    measure(() =>
        input.GetLines()
    );
    
    measure(() =>
        input.GetLines().ToList()
    );
    

    Output:

    00:00:03.9603894

    00:00:00.0029996

    00:00:04.8221971

提交回复
热议问题