views:

956

answers:

5

How do you split a string?

Lets say i have a string "dog, cat, mouse,bird"

My actual goal is to insert each of those animals into a listBox, so they would become items in a list box.

but i think i get the idea on how to insert those items if i know how to split the string. or does anyone know a better way to do this?

im using asp c#

+3  A: 
    string[] tokens = text.Split(',');

    for (int i = 0; i < tokens.Length; i++)
    {
          yourListBox.Add(new ListItem(token[i], token[i]));
    }
dove
this is beautiful, simple... and it works, but with some minor modifications though.
Adit
Might be a good idea to trim whitespace from the values...
ZombieSheep
Adyt, ZombieSheep is right, add .Trim() but guessing you got that. I wanted to illustrate as clearly the question asked and no more.
dove
+1  A: 

It gives you a string array by strVar.Split

"dog, cat, mouse,bird".Split(new[] { ',' });
codemeit
Creating a one-element char array is rather redundant. You can just pass a single char into the Split method directly.
Joel Mueller
+3  A: 

Have you tried String.Split? You may need some post-processing to remove whitespace if you want "a, b, c" to end up as {"a", "b", "c"} but "a b, c" to end up as {"a b", "c"}.

For instance:

private readonly char[] Delimiters = new char[]{','};

private static string[] SplitAndTrim(string input)
{
    string[] tokens = input.Split(Delimiters,
                                  StringSplitOptions.RemoveEmptyEntries);

    // Remove leading and trailing whitespace
    for (int i=0; i < tokens.Length; i++)
    {
        tokens[i] = tokens[i].Trim();
    }
    return tokens;
}
Jon Skeet
+2  A: 

Or simply:

targetListBox.Items.AddRange(inputString.Split(','));

Or this to ensure the strings are trimmed:

targetListBox.Items.AddRange((from each in inputString.Split(',')
    select each.Trim()).ToArray<string>());

Oops! As comments point out, missed that it was ASP.NET, so can't initialise from string array - need to do it like this:

var items = (from each in inputString.Split(',')
    select each.Trim()).ToArray<string>();

foreach (var currentItem in items)
{
    targetListBox.Items.Add(new ListItem(currentItem));
}
Gordon Mackie JoanMiro
As far as I can tell, ListBox.Items.AddRange needs a ListItem[] rather than a String[] in ASP.NET.
Jon Skeet
You could also do this with "select new ListItem(each.Trim())", to keep things in linq, if you like that sort of thing.
Ch00k
+3  A: 

Needless Linq version;

from s in str.Split(',')
where !String.IsNullOrEmpty(s.Trim())
select s.Trim();
yapiskan
I think this version simply cause it removes the empty elements...cool!
Kieron