How do you split multi-line string into lines?
I know this way
var result = input.Split(\"\\n\\r\".ToCharArray(), StringSplitOptions.RemoveEmptyEntri
private string[] GetLines(string text)
{
List<string> lines = new List<string>();
using (MemoryStream ms = new MemoryStream())
{
StreamWriter sw = new StreamWriter(ms);
sw.Write(text);
sw.Flush();
ms.Position = 0;
string line;
using (StreamReader sr = new StreamReader(ms))
{
while ((line = sr.ReadLine()) != null)
{
lines.Add(line);
}
}
sw.Close();
}
return lines.ToArray();
}
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.
You could use Regex.Split:
string[] tokens = Regex.Split(input, @"\r?\n|\r");
Edit: added |\r
to account for (older) Mac line terminators.
string[] lines = input.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);