简体   繁体   中英

C# reading a text line by line, where line delimiter is a custom

I have an array of bytes (say byte[] data), which contains text with custom line delimiters, for example: "\\r\\n" (CRLF "\\x0D\\x0A"), "\\r", "\\n", "\\x0D\\x0A\\x0D" or even "@".

At the moment I'm going to use the following solution:

  1. Normalize line breaks to CRLF (here is an example how to normalize CRLF What is a quick way to force CRLF in C# / .NET? )
  2. Use StringReader to read text line by line

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

I'm using C#, .NET 3.5. Is there any better solution?

Thanks.

Here's one option to limit calls to string.Replace to just the multi-character delimiters.

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

Then later...

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
}

请改用regexp,这将给您带来更大的灵活性。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM