Easiest way to split a string on newlines in .NET?

后端 未结 16 2339
抹茶落季
抹茶落季 2020-11-22 06:57

I need to split a string into newlines in .NET and the only way I know of to split strings is with the Split method. However that will not allow me to (easily) split on a ne

16条回答
  •  遇见更好的自我
    2020-11-22 07:25

    Try to avoid using string.Split for a general solution, because you'll use more memory everywhere you use the function -- the original string, and the split copy, both in memory. Trust me that this can be one hell of a problem when you start to scale -- run a 32-bit batch-processing app processing 100MB documents, and you'll crap out at eight concurrent threads. Not that I've been there before...

    Instead, use an iterator like this;

        public static IEnumerable SplitToLines(this string input)
        {
            if (input == null)
            {
                yield break;
            }
    
            using (System.IO.StringReader reader = new System.IO.StringReader(input))
            {
                string line;
                while( (line = reader.ReadLine()) != null)
                {
                    yield return line;
                }
            }
        }
    

    This will allow you to do a more memory efficient loop around your data;

    foreach(var line in document.SplitToLines()) 
    {
        // one line at a time...
    }
    

    Of course, if you want it all in memory, you can do this;

    var allTheLines = document.SplitToLines.ToArray();
    

提交回复
热议问题