Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split strings on carriage return with C#?

I have an ASP.NET page with a multiline textbox called txbUserName. Then I paste into the textbox 3 names and they are vertically aligned:

  • Jason
  • Ammy
  • Karen

I want to be able to somehow take the names and split them into separate strings whenever i detect the carriage return or the new line. i am thinking that an array might be the way to go. Any ideas?

thank you.

like image 793
Erica Avatar asked Nov 29 '09 03:11

Erica


2 Answers

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".

like image 107
jasonh Avatar answered Sep 18 '22 16:09

jasonh


Replace any \r\n with \n, then split using \n:

string[] arr = txbUserName.Text.Replace("\r\n", "\n").Split("\n".ToCharArray()); 
like image 32
o.k.w Avatar answered Sep 17 '22 16:09

o.k.w