Luke Zhang
Luke Zhang

Reputation: 343

c# Is there a simple way to take a multi-split array and turn it into just one, sequential array?

So basically, I have a string "one-two;three-four;five-six"

When I split ';' it becomes an array:

one-two  three-four  five-six
  [0]       [1]        [2]

Then foreach(string s in array), I split the '-', it becomes

one  two     three  four     five  six
[0]  [1]      [0]   [1]       [0]  [1]

I would like it so that it is an array like so:

one two three four five six
[0] [1]  [2]   [3]  [4] [5]

For reference, my code is pretty much the following at the moment. (Peharps I should create a list...?)

string pairsList="one-two;three-four;five-six";

string[] pairArray=pairsList.Split(';');

foreach(string s in pairArray)
{
    string[] splitPair=s.Split(',');
}

Upvotes: 0

Views: 65

Answers (2)

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391486

You can simply ask string.Split to split by the - as well.

string.Split takes a params char[] separator argument list so you can simply ask it to split by - as well:

string[] pairArray = pairsList.Split(';', '-' );

Upvotes: 2

Haney
Haney

Reputation: 34852

You're mostly there:

string pairsList="one-two;three-four;five-six";
List<string> result = new List<string>();

string[] pairArray=pairsList.Split(';');

foreach(string s in pairArray)
{
    string[] splitPair=s.Split('-');
    foreach (var thing in splitPair)
    {
        result.add(thing);
    }
}

return result.ToArray();

Even better: split on all tokens at once:

string pairsList="one-two;three-four;five-six";

string[] pairArray=pairsList.Split(';', '-');

return pairArray;

Upvotes: 1

Related Questions