Best way to split string into lines

前端 未结 10 832
情书的邮戳
情书的邮戳 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:37

    Slightly twisted, but an iterator block to do it:

    public static IEnumerable Lines(this string Text)
    {
        int cIndex = 0;
        int nIndex;
        while ((nIndex = Text.IndexOf(Environment.NewLine, cIndex + 1)) != -1)
        {
            int sIndex = (cIndex == 0 ? 0 : cIndex + 1);
            yield return Text.Substring(sIndex, nIndex - sIndex);
            cIndex = nIndex;
        }
        yield return Text.Substring(cIndex + 1);
    }
    

    You can then call:

    var result = input.Lines().ToArray();
    

提交回复
热议问题