Frey_ja
Frey_ja

Reputation: 51

Split string by second comma, then by third comma

I have a string which looks like this:

Less than $5,000, $5,000-$9,999, $10,000-$14,999, $45,000-$49,999, $50,000-$54,999

And what I would like to have is:

Less than $5,000 or $5,000-$9,999 or $10,000-$14,999 or $45,000-$49,999 or $50,000-$54,999

What I tried is:

items[1].Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries)
        .Select(e => new AnswerModel { Name = e }).ToList()

Name should be "Less than $5,000" then "$5,000-$9,999" and so on.

But it splits by every comma, I would need to split it first by the second and then by the third.

What would be the best approach?

Upvotes: 2

Views: 477

Answers (2)

Markiian Benovskyi
Markiian Benovskyi

Reputation: 2161

If your string looks exactly as you pasted here, and it will always have such pattern, then you can split on a string of two characters:

items[1].Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries);

Update:

But if your string is without spaces, then you should replace first with some unique character like |, and then split over that new character:

items[1].Replace(",$", "|$").Split(new char[1] { '|' }, StringSplitOptions.RemoveEmptyEntries);

Also you can replace it with or $ and the string would be already in desired format, and there would be no need to split and join again.

This should do the trick.

Upvotes: 2

Tim Schmelter
Tim Schmelter

Reputation: 460058

Maybe you can split by ", "

string s = "Less than $5,000, $5,000-$9,999, $10,000-$14,999, $45,000-$49,999, $50,000-$54,999";
string result = string.Join(" or ", s.Split(new []{", "},StringSplitOptions.None));

Returns your desired result:

Less than $5,000 or $5,000-$9,999 or $10,000-$14,999 or $45,000-$49,999 or $50,000-$54,999

Upvotes: 6

Related Questions