C# StreamReader, “ReadLine” For Custom Delimiters

前端 未结 4 705
长发绾君心
长发绾君心 2021-02-18 22:13

What is the best way to have the functionality of the StreamReader.ReadLine() method, but with custom (String) delimiters?

I\'d like to do something like:

4条回答
  •  野性不改
    2021-02-18 22:48

    I figured I would post my own solution. It seems to work pretty well and the code is relatively simple. Feel free to comment.

    public static String ReadUntil(this StreamReader sr, String delim)
    {
        StringBuilder sb = new StringBuilder();
        bool found = false;
    
        while (!found && !sr.EndOfStream)
        {
           for (int i = 0; i < delim.Length; i++)
           {
               Char c = (char)sr.Read();
               sb.Append(c);
    
               if (c != delim[i])
                   break;
    
               if (i == delim.Length - 1)
               {
                   sb.Remove(sb.Length - delim.Length, delim.Length);
                   found = true;
               }
            }
         }
    
         return sb.ToString();
    }
    

提交回复
热议问题