Alvin
Alvin

Reputation: 8519

String to array

I have a string :

id0:xxxxx:id0-value:xxxxx:id1:xxxxxxxx:id1-value:xxxxx:id3:xxxxxxxx:id3-value:xxx

I just need the value for idX-value from the string into array.

How can I achieve it?

Upvotes: 0

Views: 150

Answers (3)

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48600

Split it using a Regex(a regex which splits : coming after x), then split using colon : and use first index as a Dictionary Key and Second index as Dictionary value.

Upvotes: 1

cuongle
cuongle

Reputation: 75326

The simple way, the value is in position (4x - 1):

var list = input.Split(':');
var outputs = new List<string>();

for (int index = 0; index < list.Count(); index++)
{
     if (index % 4 == 3)
         outputs.Add(list.ElementAt(index));
}

Upvotes: 2

Erik Nedwidek
Erik Nedwidek

Reputation: 6184

Use String.Split()

http://msdn.microsoft.com/en-us/library/system.string.split.aspx

String myString = "id0:xxxxx:id0-value:xxxxx:id1:xxxxxxxx:id1-value:xxxxx:id3:xxxxxxxx:id3-value:xxx";
String[] tokens = myString.Split(new Char[] {':'});

The token array will contain {"id0","xxxxx","id0-value","xxxxx","id1","xxxxxxxx","id1-value","xxxxx","id3","xxxxxxxx","d3-value","xxx"}

The second possibility is to use String.IndexOf() and String.Substring().

http://msdn.microsoft.com/en-us/library/5xkyx09y http://msdn.microsoft.com/en-us/library/aka44szs

Int start = 0; ArrayList tokens; while((start = myString.IndexOf("-value:", start)) > -1) { ArrayList.Add(myString.Substring(start+6, myString.IndexOf(":", start+7); start += 6; // Jump past what we just found. }

Upvotes: 2

Related Questions