How do you split multi-line string into lines?
I know this way
var result = input.Split("\n\r".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
looks a bit ugly and loses empty lines. Is there a better solution?
If it looks ugly, just remove the unnecessary ToCharArray
call.
If you want to split by either \n
or \r
, you've got two options:
Use an array literal – but this will give you empty lines for Windows-style line endings \r\n
:
var result = text.Split(new [] { '\r', '\n' });
Use a regular expression, as indicated by Bart:
var result = Regex.Split(text, "\r\n|\r|\n");
If you want to preserve empty lines, why do you explicitly tell C# to throw them away? (StringSplitOptions
parameter) – use StringSplitOptions.None
instead.