1

I've tried googling this and looking at questions/answers on here but I'm not having much luck.

I have a list of values that I've already put into an array by splitting on the commas (","), but now I need to split on the colons (":"). I am at a loss for how to do this, everything I've tried so far hasn't working and I can't figure out how to fix it.

string AdditionalData = "Name: John, Age: 43, Location: California";
string[] firstData = AdditionalData.Split(',');

The above code is how far I've gotten - this works - but no matter what I try I can't figure out how to split the data on the colon. Basically, I'm looking to take the array "firstData" and make that into a new array.

Any help would be appreciated and apologies for the simplicity of the question, I'm new to this!

Side note: This is part of an asp.net mvc project if that is of any help, the tag was removed. the results are also displayed as a web page, not in the console.

4
  • 6
    You need to tell us what you expect the end data structure to be. It could be as simple as: AdditionalData.Split(new[] { ',', ':' }); Commented Jul 31, 2018 at 15:44
  • So the desired result is a string[][]? Commented Jul 31, 2018 at 15:46
  • What do you actually want as an end result? i.e what are you trying to do with the data? Commented Jul 31, 2018 at 16:04
  • @SteveJ In the end I want to be able to take the values from the second split, i.e, "John","43","California" and assign them to a model that already exists. This preexisting model will then be displayed as part of another, larger model. Commented Jul 31, 2018 at 16:31

2 Answers 2

2

Iterate each array item using a foreach loop.

foreach(string dataString in firstData)
{
  string[] temp = dataString.Split(':')
  //do something with the new array here
}
Sign up to request clarification or add additional context in comments.

3 Comments

This worked beautifully and was by far the easiest for me to understand, thank you!
@Chilly Make sure Accept the answer that works for you. It helps people that find this question in the future and you get rep for it!
@itsme86 yes I will do, I'm just in the habit of leaving things open for a day or so to allow people to answer, sometimes they don't when they see an accepted answer when it could be very useful :)
0

I guess this is what you want, but I'm not sure.

var secondData = firstData.Select(str => str.Split(':'));

Comments

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.