Split a string and join it back together in a different order?

Posted by Xaisoft on Stack Overflow See other posts from Stack Overflow or by Xaisoft
Published on 2012-10-24T16:51:12Z Indexed on 2012/10/24 17:00 UTC
Read the original article Hit count: 159

Filed under:

What is the most concise, yet readable way to split a string and put join it back together in a different order. For example, I want to split the following string:

10-20-30-4000-50000 and I would do this via:

string[] tokens = original.Split('-');

and now I want to put it back together in this order:

30-20-10-4000-50000

I know I can use Join to put it back together in it's original form, but I don't want that. The only thing I can think of right now is:

string modified = string.Format("{0}{1}{2}{3}{4}",tokens[2],tokens[1],tokens[0],tokens[3], tokens[4]);

I realized that if I do:

string modified = string.Format("{2}{1}{0}{3}{4}", tokens);

it does not keep the dashes which is what I want so is to do that, should I just do:

string modified = string.Format("{2}-{1}-{0}-{3}-{4}", tokens);

© Stack Overflow or respective owner

Related posts about c#