我想将字符串拆分为 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"
但这不是我要找的。 我怎样才能做到这一点?任何帮助将非常感激。谢谢。
最佳答案
如何用空格拆分,迭代到最后一项,然后将两个带格式的项目放入该列表?
string str = "I want to split the string into 2 words";
var array = str.Split(' ');
var list = new List<string>();
for (int i = 0; i < array.Length - 1; i++)
{
list.Add(string.Format("{0} {1}", array[i], array[i + 1]));
}
关于c# - 在 C# 中设置的 2 个单词字符串中拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34922453/