C# StreamReader, “ReadLine” For Custom Delimiters

前端 未结 4 706
长发绾君心
长发绾君心 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 23:02

    Here is a simple parser I used where needed (usually if streaming is not a paramount just read and .Split does the job), not too optimized but should work fine:
    (it's more of a Split like method - and more notes below)

        public static IEnumerable Split(this Stream stream, string delimiter, StringSplitOptions options)
        {
            var buffer = new char[_bufffer_len];
            StringBuilder output = new StringBuilder();
            int read;
            using (var reader = new StreamReader(stream))
            {
                do
                {
                    read = reader.ReadBlock(buffer, 0, buffer.Length);
                    output.Append(buffer, 0, read);
    
                    var text = output.ToString();
                    int id = 0, total = 0;
                    while ((id = text.IndexOf(delimiter, id)) >= 0)
                    {
                        var line = text.Substring(total, id - total);
                        id += delimiter.Length;
                        if (options != StringSplitOptions.RemoveEmptyEntries || line != string.Empty)
                            yield return line;
                        total = id;
                    }
                    output.Remove(0, total);
                }
                while (read == buffer.Length);
            }
    
            if (options != StringSplitOptions.RemoveEmptyEntries || output.Length > 0)
                yield return output.ToString();
        }
    

    ...and you can simply switch to char delimiters if needed just replace the

    while ((id = text.IndexOf(delimiter, id)) >= 0)
    

    ...with

    while ((id = text.IndexOfAny(delimiters, id)) >= 0)
    

    (and id++ instead of id+= and a signature this Stream stream, StringSplitOptions options, params char[] delimiters)

    ...also removes empty etc.
    hope it helps

提交回复
热议问题