简体   繁体   English

按第二个逗号分隔字符串,然后按第三个逗号

[英]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 少于$ 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 少于$ 5,000或$ 5,000- $ 9,999或$ 10,000- $ 14,999或$ 45,000- $ 49,999或$ 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. 名称应为“少于$ 5,000”,然后为“ $ 5,000- $ 9,999”,依此类推。

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? 最好的方法是什么?

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 少于$ 5,000或$ 5,000- $ 9,999或$ 10,000- $ 14,999或$ 45,000- $ 49,999或$ 50,000- $ 54,999

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. 同样,您也可以用or $替换它,并且该字符串将已经具有所需的格式,并且无需拆分和重新加入。

This should do the trick. 这应该可以解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM