66

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.

Aify
  • 3,543
  • 3
  • 24
  • 43
Erica
  • 675
  • 1
  • 5
  • 4

7 Answers7

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

jasonh
  • 29,297
  • 11
  • 59
  • 61
  • 5
    Is there a guarantee that this wouldn't first split by \n, leaving \r\n reduced to \r? – spender Nov 29 '09 at 03:47
  • I'm pretty sure it won't. I use this line in my app at work and it's used to parse the clipboard one at a time (somehow users have a need for UNIX line-endings on Windows...). However, if it does, I imagine that reversing the strings in the string array argument would solve this. Does anyone know how to generate a mix of the two to test with? – jasonh Nov 29 '09 at 03:50
  • 9
    @jasonh: "I'm pretty sure"... famous last words. :) – Esteban Araya Nov 29 '09 at 03:56
  • @jasonh: with tools and apps being used on both Windows and Linux, the lines are being blurred a bit, and in reality any application running on either should be able to handle either line ending gracefully. – Matthew Scharley Nov 29 '09 at 04:04
  • @Esteban Araya: LOL! I revised my answer with test code showing that it passes with flying colors. :) – jasonh Nov 29 '09 at 04:08
  • Thanks a lot jasonh, your example is just great. I just tested it and it works great. all the strings are ordered in the array in the same order they were entered too. – Erica Nov 29 '09 at 04:10
  • @spender: Of course there's a gurantee. You'll get 3x you money back if you get fired by your boss if the code splits the lines incorrectly. :P – Esteban Araya Nov 29 '09 at 04:14
  • 16
    If you want to be sure of splitting on all combinations of CR or LF then you can do this: `string[] result = input.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);` – LukeH Nov 29 '09 at 10:08
  • If you wish to keep the empty lines, use `string[] result = input.Split(new char[] { '\r', '\n' }, StringSplitOptions.None);` – Kraang Prime Apr 07 '16 at 15:22
  • In my case, the string sometimes contained \r, so I needed to add that to the Split arguments result = input.Split(new char[] { '\r', '\n', '\r\n' }, StringSplitOptions.RemoveEmptyEntries); – Kappacake Feb 07 '18 at 10:41
7

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

string[] arr = txbUserName.Text.Replace("\r\n", "\n").Split("\n".ToCharArray());
o.k.w
  • 25,490
  • 6
  • 66
  • 63
4

Take a look at the String.Split function (not sure of exact syntax, no IDE in front of me).

string[] names = txbUserName.Text.Split(Environment.Newline);
Liam
  • 27,717
  • 28
  • 128
  • 190
TryCatch
  • 61
  • 2
  • 2
    Environment.Newline is the "newline" representation of the server's environment, it doesn't control what the user can input, does it? – o.k.w Nov 29 '09 at 03:55
  • 1
    If a constant could control what the user could input, well I'd buy more Microsoft stock... a *lot* more. – TryCatch Nov 29 '09 at 04:03
  • FWIW - it's better to use "\r" and/or "\n", my answer focuses more on the "just use .split" to break the string up. Just be glad you don't have to write .split in C and manage the memory and pointers yourself! Young whipper-snappers got it easy I tell ya. – TryCatch Nov 29 '09 at 04:08
1

String.Split?

mystring.Split(new Char[] { '\n' })
Thanatos
  • 42,585
  • 14
  • 91
  • 146
1
using System.Text;
using System.Text.RegularExpressions;


 protected void btnAction_Click(object sender, EventArgs e)
    {
        string value = txtDetails.Text;
        char[] delimiter = new char[] { ';','[' };
        string[] parts = value.Split(delimiter, StringSplitOptions.RemoveEmptyEntries);
        for (int i = 0; i < parts.Length; i++)
        {
            txtFName.Text = parts[0].ToString();
            txtLName.Text = parts[1].ToString();
            txtAge.Text = parts[2].ToString();
            txtDob.Text = parts[3].ToString();
        }
    }
Peter O.
  • 32,158
  • 14
  • 82
  • 96
Rubi
  • 9
  • 1
0

Try this:

message.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

Works if :

var message = "test 1\r\ntest 2";

Or

var message = "test 1\ntest 2";

Or

var message = "test 1\rtest 2";
Tovich
  • 535
  • 1
  • 5
  • 15
0

It depends what you want to do. Another option, which is probably overkill for small lists, but may be more memory efficient for larger strings, is to use the StringReader class and use an enumerator:

IEnumerable<string> GetNextString(string input)
{
    using (var sr = new StringReader(input))
    {
        string s;
        while ((s = sr.ReadLine()) != null)
        {
            yield return s;
        }
    }
}

This supports both \n and \r\n line-endings. As it returns an IEnumerable you can process it with a foreach, or use any of the standard linq extensions (ToList(), ToArray(), Where, etc).

For example, with a foreach:

var ss = "Hello\nworld\r\ntwo bags\r\nsugar";
foreach (var s in GetNextString(ss))
{
    Console.WriteLine("==> {0}", s);
}
Chris J
  • 30,688
  • 6
  • 69
  • 111