我想將字符串拆分爲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
它是一個動態字符串。所以我需要像我之前提到的那樣將其分成兩組單詞列表。 –
什麼被認爲是這個任務的一個詞?任何空間之間的東西? –