我想从用户那里取一个数字N
并根据该数字拆分数组并将新元素保存为新数据。
例如,当用户输入2时,我有一个类似
的数组["alameeer", "alameer", "alameer", "alameer", "alameer", "ashraf"]
结果将是
["alameeer", "alameer"], ["alameeer", "alameer"], ["alameeer", "ashraf"]
当N等于3
时["alameeer", "alameer", "alameeer"], ["alameeer", "alameer", "alameeer"]
我尝试了以下代码,但它非常静态且性能非常差,我不知道如何更改它。
string str = UserCorpus.TrimEnd();
string[] Oops = str.Split(' ', ',', '!');
int stringCounter = Oops.Length;
string[] holder = new string[10];
for (int i = 0; i < stringCounter - 2; i++)
{
holder[i] = Oops[i] + Oops[i + 1] + Oops[i + 2];
}
答案 0 :(得分:1)
你不应该担心这里的表现不好。你试图做的事情要比O(n)
好。
我怎么建议你使用MoreLinq批处理。它也是由jon双向飞碟写的,有什么问题吗? ;)
string[] array = new[] {"alameeer", "alameer", "alameer", "alameer", "alameer", "ashraf"};
int cut = 2;
var result = array.Batch(cut, piece => string.Join(" ", piece)).ToArray();
如果你想编写自己的实现,你可以这样做。适用于任何切割长度和阵列长度。 (我怀疑这个是O(n)
因为我认为Skip(i)
不是O(1)
)
string[] array = new[] {"alameeer", "alameer", "alameer", "alameer", "alameer", "ashraf"};
int cut = 2;
string[] result = new string[(int)Math.Ceiling(array.Length / (double)cut)];
for (int i = 0, j = 0; i < array.Length; i += cut, j++)
{
result[j] = string.Join(" ", array.Skip(i).Take(cut));
}
如果您根本不想使用Linq。 (O(n)
)
string[] array = new[] { "alameeer", "alameer", "alameer", "alameer", "alameer", "ashraf" };
int cut = 4;
string[] result = new string[(int)Math.Ceiling(array.Length / (double)cut)];
for (int i = 0, j = 0; i < array.Length; i += cut, j++)
{
string[] temp = new string[Math.Min(cut, array.Length)];
for (int k = i; k < i + cut && k < array.Length; k++)
{
temp[k - i] = array[k];
}
result[j] = string.Join(" ", temp).Trim();
}