C#中的StreamReader,"&的ReadLine QUOT;对于自定义分隔符 [英] C# StreamReader, "ReadLine" For Custom Delimiters

查看:146
本文介绍了C#中的StreamReader,"&的ReadLine QUOT;对于自定义分隔符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是有 StreamReader.ReadLine()方法的功能的最佳方式,而是使用自定义(字符串)分隔符?

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

我想要做的是这样的:

String text;
while((text = myStreamReader.ReadUntil("my_delim")) != null)
{
   Console.WriteLine(text);
}



我试图让我自己使用皮克() 的StringBuilder ,但它的效率太低。我在寻找的建议或可能是一个开源的解决方案。

I attempted to make my own using Peek() and StringBuilder, but it's too inefficient. I'm looking for suggestions or possibly an open-source solution.

感谢。

修改

我应该澄清了早先......我见过的这个答案,但是,我不希望将整个文件读入内存。

I should have clarified this earlier...I have seen this answer, however, I'd prefer not to read the entire file into memory.

推荐答案

我想我会发布我自己的解决方案。这似乎工作得很好,代码也比较简单。随意发表评论。

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

这篇关于C#中的StreamReader,&QUOT;&的ReadLine QUOT;对于自定义分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆