2016-01-21 56 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個單詞。