我想将字符串拆分为2个字符串集合。例如,在c中设置2个字符串中的字符串拆分#
string str = "I want to split the string into 2 words"
输出应该是这样的:
1: "I want"
2: "want to"
3: "to split"
4: "split the"
5: "the string"
6: "string into"
7: "into 2"
8: "2 words"
应该是什么做到这一点的最好方法是什么?
我试过这种方式,
var pairs = textBox1.Text.Split(' ')
.Select((s, i) => new { s, i })
.GroupBy(n => n.i/2)
.Select(g => string.Join(" ", g.Select(p => p.s)))
.ToList();
但它不工作。我得到了以下字符串集。
1: "I want"
2: "to split"
3: "the string"
4: "into 2"
5: "words"
但这不是我要找的。 我该如何做到这一点?任何帮助将非常感激。谢谢。
你介意编辑字符串还是必须保持原样。否则,你可以添加一个' - '符号或什么,然后用它来分割它?否则,一个简单的for循环会在每隔一个循环忽略它的地方执行。 – James
它是一个动态字符串。所以我需要像我之前提到的那样将其分成两组单词列表。 –
什么被认为是这个任务的一个词?任何空间之间的东西? –