我在c#中有一个字符串。我想将该字符串拆分为2个字符串集,如:
string str = "Split handles splitting upon string and character delimiters."
输出应为:
1: "Split handles"
2: "splitting upon"
3: "string and"
4: "character delimiters."
这样做的最佳方法是什么?
以下是我的尝试:
private List<string> Spilt(string text)
{
List<string> bunch = new List<string>();
int block = 15;
string[] words = text.Split(' ');
int length = words.Length;
int remain = 0;
while(remain < length)
{
bunch.Add(string.Join(" ", words.Take(block)));
remain += block;
}
return bunch;
}
答案 0 :(得分:5)
最简单的方法是在每个空间拆分,然后重新加入&#34;对回来,像这样:
var pairs = str.Split(' ')
.Select((s,i) => new {s, i})
.GroupBy(n => n.i / 2)
.Select(g => string.Join(" ", g.Select(p=>p.s)))
.ToList();
答案 1 :(得分:0)
试试这个
string str = "Split handles splitting upon string and character delimiters.";
var strnew = str.Split(' ');
var strRes = string.Empty;
int j = 1;
for (int i = 0; i < strnew.Length; i=i+2)
{
strRes += j.ToString()+": " + @"""" + strnew[i] + " " + strnew[i+1] + @"""" +"\n" ;
j++;
}
Console.Write(strRes);
// print strRes