c# - 在 C# 中设置的 2 个单词字符串中拆分字符串

标签 c# regex string

我想将字符串拆分为 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]));
}

enter image description here

关于c# - 在 C# 中设置的 2 个单词字符串中拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34922453/

相关文章:

javascript - 如何使用带有变量的 RegEx 进行替换

c# - 如果它是一个字符串,如何测试空值变量?

c# - 在 WPF C# TreeView 中获取子节点的父节点

c# - 使用 AutoFixture 中的 CreateMany 省略特定字段

c# - (UWP) 当你 x :Bind an event to a eventhandler in VM, 导航到新 View 时是否必须手动取消绑定(bind)?

c - 扫描不同类型的变量

python - 将float转换为str时如何检查默认小数精度?

c# - 使用 COM 将数组从 C# 返回到经典 ASP

java - 用 "$"替换时 replaceFirst() 失败

r - 在 gregexpr 和 str_extract_all 函数中进行量化的交替