How to split strings on carriage return with C#?
string[] result = input.Split(new string[] {"\n", "\r\n"}, StringSplitOptions.RemoveEmptyEntries);
This covers both \n and \r\n newline types and removes any empty lines your users may enter.
I tested using the following code:
string test = "PersonA\nPersonB\r\nPersonC\n";
string[] result = test.Split(new string[] {"\n", "\r\n"}, StringSplitOptions.RemoveEmptyEntries);
foreach (string s in result)
Console.WriteLine(s);
And it works correctly, splitting into a three string array with entries "PersonA", "PersonB" and "PersonC".
Replace any \r\n
with \n
, then split using \n
:
string[] arr = txbUserName.Text.Replace("\r\n", "\n").Split("\n".ToCharArray());