【问题标题】:C# reading a text line by line, where line delimiter is a customC#逐行读取文本,其中行分隔符是自定义的
【发布时间】:2010-01-02 17:31:19
【问题描述】:

我有一个字节数组(比如 byte[] 数据),其中包含带有自定义行分隔符的文本,例如:"\r\n" (CRLF "\x0D\x0A")、"\r"、" \n”、“\x0D\x0A\x0D”甚至“@”。

目前我将使用以下解决方案:

  1. 将换行符标准化为 CRLF(这里是如何标准化 CRLF What is a quick way to force CRLF in C# / .NET? 的示例)
  2. 使用StringReader逐行读取文本

    
    using (String Reader sr = new StringReader(data.ToString()))
    {
        string line;
        while ((line = sr.ReadLine()) != null)
        {
            // Process the line 
        }
    }
    

我正在使用 C#、.NET 3.5。 有没有更好的解决方案?

谢谢。

【问题讨论】:

  • 你应该将你的行尾规范化为 \n,它只需要 2 个替换而不是 3 个。请注意,在你的链接中,答案首先规范化为 \n,然后才将 \n 更改为\r\n.
  • 是的,事实证明我需要将行结尾标准化为以下任一:“\r”、“\n”、“\r\n”msdn.microsoft.com/en-us/library/… 一行定义为一系列字符后跟换行符 ("\n")、回车符 ("\r") 或回车符后紧跟换行符 ("\r\n")。结果字符串不包含终止回车和/或换行。如果已到达底层字符串的末尾,则返回值为空引用(在 Visual Basic 中为 Nothing)。
  • 为了获得最快的性能,您可以手动拆分它...

标签: c# .net


【解决方案1】:

这里有一个选项可以限制对 string.Replace 的调用仅限于多字符分隔符。

private static readonly char[] DelimiterChars = { '\r', '\n', '@' };
private static readonly string[] DelimiterStrings = { "\r\n\r", "\r\n" };

然后……

string text = Encoding.ASCII.GetString(data);
foreach (string delim in DelimiterStrings)
    text = text.Replace(delim, "\n");

foreach (string line in text.Split(DelimiterChars))
{
    // processing here
}

【讨论】:

    【解决方案2】:

    改用正则表达式,这将为您提供更大的灵活性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-21
      • 2017-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-15
      • 2011-09-22
      • 1970-01-01
      相关资源
      最近更新 更多