How can I convert a string with newlines in it to separate lines?

前端 未结 5 390
感情败类
感情败类 2021-01-23 21:46

How to convert string that have \\r\\n to lines?

For example, take this string:

string source = \"hello \\r\\n this is a test \\r\\n tested\         


        
5条回答
  •  北恋
    北恋 (楼主)
    2021-01-23 22:43

    For clarity I have made another answer.

    I have made these two extension methods:

    ReadLines will let you read one line at the time without parsing the whole string into an array. ReadAllLines will parse the whole line into an array.

    In your case, you can use it like:

    var lines = source.ReadAllLines();
    

    I have taken the names from File.ReadLines and File.ReadAllLines so they should be consistent with the rest of .Net framework.

    As a side note to comments on my other answer, I have checked StringReader.ReadLine´s code and this do take care of both \r\n and \n - but not the old legacy Mac Os etc. (shouldn't be important).

    public static class StringExtensions
    {
        public static IEnumerable ReadLines(this string data)
        {
            using (var sr = new StringReader(data))
            {
                string line;
    
                while ((line = sr.ReadLine()) != null)
                    yield return line;
            }
        }
    
        public static string[] ReadAllLines(this string data)
        {
            var res = new List();
    
            using (var sr = new StringReader(data))
            {
                string line;
    
                while ((line = sr.ReadLine()) != null)
                    res.Add(line);
            }
    
            return res.ToArray();
        }
    }
    

    (ReadAllLines could have been made with ReadLines.ToArray but I decided that the extra few lines of code was better than an wrapped IEnumerable which takes some processing time)

提交回复
热议问题