如何将字符串拆分为五个一组? [英] How to Split a string into groups of five?
本文介绍了如何将字符串拆分为五个一组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个字符串:
I have this string:
string="101,102,103,105,201,250,2564,245564,212,2415,2102,5645,656";
我想把它分成5组。
输出应该是:
I want to split it into groups of 5.
Output should be:
array[0]=101,102,103,105,201
[1]=250,2564,245564,212,2415
[2]=2102,5645,656
推荐答案
请看我对这个问题的评论:你没有真正定义wh在你想要实现。
问题太简单了。您只需要两件事情1)正确定义您的要求,2): http:/ /msdn.microsoft.com/en-us/library/system.string.split.aspx [ ^ ]。
可能你的意思是你想要分割项目由','分隔的5个元素组,并将剩余元素(小于或等于5)放在最后一个组中。如果是这样,你还需要知道这个:
http:// msdn。 microsoft.com/en-us/library/3b1ff23f.aspx [ ^ ],
http:// msdn.microsoft.com/en-us/library/0w4e0fzs.aspx [ ^ ]。 :-)
-SA
Please see my comment to the question: you did not really define what you want to achieve.
The problem is way too simple. You need just two things 1) correct definition of your requirements, 2) this: http://msdn.microsoft.com/en-us/library/system.string.split.aspx[^].
Probably you mean that you want to split the items by groups of 5 elements delimited by ',' and put the remaining elements (less or equal than 5) in a last group. If so, you also need to know this:
http://msdn.microsoft.com/en-us/library/3b1ff23f.aspx[^],
http://msdn.microsoft.com/en-us/library/0w4e0fzs.aspx[^]. :-)
—SA
从脑到纸:
From Brain-To-Paper:
string pattern = @"(?:^|,)(\d+(?:,\d+){1,4})";
var array = Regex.Matches(input, pattern)
.Cast<Match>()
.Select(m=>m.Groups[1].Value)
.ToArray();
假设字符串形成良好的工作。
我已经测试了上面的代码并且它有效(所以,没有了从脑到 - 纸)。下面的代码是废话,但是 - 抱歉错误的提示:-(
或者
This should work assuming the string is well formed.
I've tested the above code and it works (so, no any more "from-brain-to-paper"). The code below is crap, though - sorry for the wrong hint :-(
Alternatively
IEnumerable<string> GetChunks(string input)
{
var elements = input.Split(new char[]{','});
foreach(var chunk in elements.Take(5))
{
yield return string.Join(",", chunk);
}
}
var array = GetChunks(input).ToArray();
[/ EDIT]
干杯
Andi
[/EDIT]
Cheers
Andi
string str ="101,102,103,105,201,250,2564,245564,212,2415,2102,5645,656,444,555";
string[] arl = str.Split(',');
if (arl.Length > 5)
{
string[] strResult;
int totCount = arl.Length / 5;
int totReminder = arl.Length % 5;
if (totReminder > 0)
{
strResult = new string[totCount + 1];
}
else
{
strResult = new string[totCount];
}
for (int i = 0; i < totCount; i++)
{
strResult[i] = arl[i].ToString() + "," + arl[i + 1].ToString() + "," + arl[i + 2].ToString() + "," + arl[i + 3].ToString() + "," + arl[i + 4].ToString();
}
if (totReminder > 0)
{
for (int i = 5 * totCount; i < arl.Count(); i++)
{
strResult[strResult.Length - 1] = strResult[strResult.Length - 1] + arl[i];
if (i < (arl.Count() - 1))
{
strResult[strResult.Length - 1] = strResult[strResult.Length - 1] + ",";
}
}
}
}
else
{
//do the needFull
}
>
这篇关于如何将字符串拆分为五个一组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文