将字符串拆分为行的最佳方法

时间:2009-10-02 07:49:05

标签: c# string syntax multiline

如何将多行字符串拆分成行?

我知道这种方式

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

看起来有点难看并且丢失了空行。有更好的解决方案吗?

11 个答案:

答案 0 :(得分:146)

  • 如果看起来很难看,只需删除不必要的ToCharArray电话。

  • 如果您要按\n\r进行拆分,则有两种选择:

    • 使用数组文字 - 但这会为您提供Windows样式行结尾的空行\r\n

      var result = text.Split(new [] { '\r', '\n' });
      
    • 使用正则表达式,如Bart所示:

      var result = Regex.Split(text, "\r\n|\r|\n");
      
  • 如果你想保留空行,为什么要明确告诉C#扔掉它们? (StringSplitOptions参数) - 改为使用StringSplitOptions.None

答案 1 :(得分:107)

using (StringReader sr = new StringReader(text)) {
    string line;
    while ((line = sr.ReadLine()) != null) {
        // do something
    }
}

答案 2 :(得分:36)

你可以使用Regex.Split:

string[] tokens = Regex.Split(input, @"\r?\n|\r");

修改:添加|\r以考虑(较旧的)Mac线路终结器。

答案 3 :(得分:36)

更新:有关备用​​/异步解决方案,请参阅here


这很有效,比Regex更快:

input.Split(new[] {"\r\n", "\r", "\n"}, StringSplitOptions.None)

在数组中首先"\r\n"是很重要的,这样才能将其作为一个换行符。以上结果与这些Regex解决方案的结果相同:

Regex.Split(input, "\r\n|\r|\n")

Regex.Split(input, "\r?\n|\r")

除了Regex的速度慢了大约10倍。这是我的考试:

Action<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(() =>
    Regex.Split(input, "\r\n|\r|\n")
);

measure(() =>
    Regex.Split(input, "\r?\n|\r")
);

<强>输出:

00:00:03.8527616

00:00:31.8017726

00:00:32.5557128

这里是扩展方法:

public static class StringExtensionMethods
{
    public static IEnumerable<string> GetLines(this string str, bool removeEmptyLines = false)
    {
        return str.Split(new[] { "\r\n", "\r", "\n" },
            removeEmptyLines ? StringSplitOptions.RemoveEmptyEntries : StringSplitOptions.None);
    }
}

<强>用法:

input.GetLines()      // keeps empty lines

input.GetLines(true)  // removes empty lines

答案 4 :(得分:8)

如果你想保留空行,只需删除StringSplitOptions。

var result = input.Split(System.Environment.NewLine.ToCharArray());

答案 5 :(得分:4)

我有这个other answer但是这个基于杰克的answer明显更快可能是首选,因为它异步工作,虽然稍慢。

public static class StringExtensionMethods
{
    public static IEnumerable<string> 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;
            }
        }
    }
}

<强>用法:

input.GetLines()      // keeps empty lines

input.GetLines(true)  // removes empty lines

<强>测试

Action<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()
);

<强>输出:

00:00:03.9603894

00:00:00.0029996

00:00:04.8221971

答案 6 :(得分:2)

略微扭曲,但迭代器阻止这样做:

public static IEnumerable<string> 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);
}

然后你可以打电话:

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

答案 7 :(得分:2)

      char[] archDelim = new char[] { '\r', '\n' };
      words = asset.text.Split(archDelim, StringSplitOptions.RemoveEmptyEntries); 

答案 8 :(得分:1)

    private string[] GetLines(string text)
    {

        List<string> lines = new List<string>();
        using (MemoryStream ms = new MemoryStream())
        {
            StreamWriter sw = new StreamWriter(ms);
            sw.Write(text);
            sw.Flush();

            ms.Position = 0;

            string line;

            using (StreamReader sr = new StreamReader(ms))
            {
                while ((line = sr.ReadLine()) != null)
                {
                    lines.Add(line);
                }
            }
            sw.Close();
        }



        return lines.ToArray();
    }

答案 9 :(得分:1)

正确处理 混合 行尾是很棘手的。众所周知,行终止符可以是“换行符”(ASCII 10,\n\x0A\u000A),“回车”(ASCII 13,\r) ,\x0D\u000D)或它们的某种组合。回到DOS,Windows使用两个字符的序列CR-LF \u000D\u000A,因此此组合仅发出一行。 Unix使用单个\u000A,非常老的Mac使用单个\u000D字符。在单个文本文件中处理这些字符的任意混合的标准方法如下:

  • 每个CR或LF字符都应跳到下一行 EXCEPT ...
  • ...如果CR后面紧跟着LF(\u000D\u000A),则这两个一起只会跳过一行。
  • String.Empty是唯一不返回任何行的输入(任何字符至少需要一行)
  • 即使没有CR和LF,也必须返回最后一行。

前面的规则描述了StringReader.ReadLine和相关函数的行为,下面显示的函数产生相同的结果。它是有效的 C#换行功能,可以忠实地实施这些准则,以正确处理CR / LF的任意顺序或组合。列举的行不包含任何CR / LF字符。空行将保留并作为String.Empty返回。

/// <summary>
/// Enumerates the text lines from the string, handling mixed CR-LF scenarios correctly.
/// </summary>
public static IEnumerable<String> Lines(this String s)
{
    int j = 0, c, i;
    char ch;
    if ((c = s.Length) > 0)
        do
        {
            for (i = j; (ch = s[j]) != '\r' && ch != '\n' && ++j < c;)
                ;

            yield return s.Substring(i, j - i);
        }
        while (++j < c && (ch != '\r' || s[j] != '\n' || ++j < c));
}

注意:如果您不介意在每次调用中创建一个StringReader实例的开销,则可以改用以下 C#7 代码。如上所述,虽然上面的示例可能更有效,但是这两个函数产生的结果完全相同。

public static IEnumerable<String> Lines(this String s)
{
    using (var tr = new StringReader(s))
        while (tr.ReadLine() is String L)
            yield return L;
}

答案 10 :(得分:1)

将字符串拆分成行,无需任何分配。

public static LineEnumerator GetLines(this string text) {
    return new LineEnumerator( text.AsSpan() );
}

internal ref struct LineEnumerator {

    private ReadOnlySpan<char> Text { get; set; }
    public ReadOnlySpan<char> Current { get; private set; }

    public LineEnumerator(ReadOnlySpan<char> text) {
        Text = text;
        Current = default;
    }

    public LineEnumerator GetEnumerator() {
        return this;
    }

    public bool MoveNext() {
        if (Text.IsEmpty) return false;

        var index = Text.IndexOf( '\n' ); // \r\n or \n
        if (index != -1) {
            Current = Text.Slice( 0, index + 1 );
            Text = Text.Slice( index + 1 );
            return true;
        } else {
            Current = Text;
            Text = ReadOnlySpan<char>.Empty;
            return true;
        }
    }


}
相关问题