Jannis Höschele
Jannis Höschele

Reputation: 147

Switch parts of a string

I've got a list of strings that look like this

String s = "Top-0001-V[5]"

and I need to switch the parts to this Pattern:

String sF = "0001-Top-V-[5]"

I already tried to split them at "-" and then adding them, but the problem is it's a really long line of code, is there a way of doing this in an easy way, or do i have to split it all the way up and add it back togehther?

Upvotes: 2

Views: 199

Answers (2)

Mohit S
Mohit S

Reputation: 14044

This might do the trick for you

var items = s.Split('-');
items[items.Length - 1] =  items[items.Length - 1].Replace("[","-[");
string x = String.Format("{0}-{1}-{2}", items[1], items[0], items[2]);

The output will be

0001-Top-V-[5]

You can also use String.Substring if the format of the string is common because String.Substring Retrieves a substring from this instance. The substring starts at a specified character position and has a specified length.

Upvotes: 3

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37000

A Regex might help:

var r = new Regex("(Top)-(\\d+)-(V)\\[(\\d+)\\]");
string result = r.Replace(myInout, "$2-$1-$3-[$4]")

Upvotes: 3

Related Questions