0

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?

2
  • Tried anything or totally clueless? Commented Aug 16, 2012 at 3:27
  • Good place for some Regex! One word... Match Collection. Commented Aug 16, 2012 at 3:28

3 Answers 3

2

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));
}
Sign up to request clarification or add additional context in comments.

2 Comments

The string can be dynamic, more then 3 values.
it can be id0:xxxxx:id0-value:xxxxx:id1:xxxxxxxx:id1-value:xxxxx:id3:xxxxxxxx:id3-value:xxx , or id0:xxxxx:id0-value:xxxxx:id1:xxxxxxxx:id1-value:xxxxx:id3:xxxxxxxx:id3-value:xxx:id4:xxxxxxxx:id4-value:xxx
2

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

Comments

1

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.

1 Comment

The reason I wouldn't recommend RegEx is because the data appears to be in a set pattern. RegEx compilation and usage is expensive both in terms of CPU and memory in comparison to just splitting the string. If the data is not in a clear pattern, then RegEx is the way to go.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.