How do i split a String into multiple values?

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#

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

    string[] tokens = text.Split(',');

    for (int i = 0; i < tokens.Length; i++)
    {
          yourListBox.Add(new ListItem(token[i], token[i]));
    }

Method 2

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;
}

Method 3

Needless Linq version;

from s in str.Split(',')
where !String.IsNullOrEmpty(s.Trim())
select s.Trim();

Method 4

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));
}

Method 5

It gives you a string array by strVar.Split

"dog, cat, mouse,bird".Split(new[] { ',' });


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x