2016-01-21 21 views
1

我想将字符串拆分为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" 

但这不是我要找的。 我该如何做到这一点?任何帮助将非常感激。谢谢。

+0

你介意编辑字符串还是必须保持原样。否则,你可以添加一个' - '符号或什么,然后用它来分割它?否则,一个简单的for循环会在每隔一个循环忽略它的地方执行。 – James

+0

它是一个动态字符串。所以我需要像我之前提到的那样将其分成两组单词列表。 –

+0

什么被认为是这个任务的一个词?任何空间之间的东西? –

回答

3

如何用空格分隔,迭代到最后一个项目,并将两个格式化项目放入该列表中?

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

+0

谢谢巴迪。它的工作.. –

2

首先,你所做的一切,通过空间分割每一个单词,像这样:

String[] words = str.Split(' ') 

现在,只需通过查看此数组并连接两对每个串时间变成一个新的阵列。

String[] pairs = new String[words.Length - 1]; 

for (int i = 0; i+1 < words.length; i++) 
{ 
    pairs[i] = string.Format("{0} {1}", words[i], words[i+1]); 
} 

此代码可能在语法上不正确,但这个想法可行!

1

我只是想分享一个正则表达式的方法:

var s = "I want to split the string into 2 words"; 
var result = Regex.Matches(s, @"(\w+)(?=\W+(\w+))") 
       .Cast<Match>() 
       .Select(p => string.Format("{0} {1}", p.Groups[1].Value, p.Groups[2].Value)) 
       .ToList(); 

IDEONE demo

随着(\w+)(?=\W+(\w+))regex,我们要确保我们捕获一个字((\w+)),然后捕捉下一个单词,但不消耗它带有前瞻性((?=\W+(\w+)))(使用(\w+))但省略了非单词字符(\W+)。然后我们只加入Select中的2个单词。