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\
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)