所以我正在解决一些不相关的编码挑战,我需要根据一个元素拆分一个int数组。
类似于String。分裂。
例如:
var arr1 = new int [] { 3, 3, 0, 2, 4, 3, 2 };
var arr2 = new int [] { 8, 8, 5, 7, 9, 8, 7, 4, 8 };
var results1 = Split(arr1, 0);
foreach (var arr in results1)
Console.WriteLine(string.Join(",", arr));
var results2 = Split(arr2, 8);
foreach (var arr in results2)
Console.WriteLine(string.Join(",", arr));
这里的输出是:
33
2、4、3、2
5、7、9
7 4
我很惊讶,我找不到任何答案,字符串。分割一直出现,但没有整数!
所以我这样写:
public int[][] Split(int[] arr, int element)
{
List<int[]> arrays = new List<int[]>();
int skip = 0;
int take = 0;
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] == element && take != 0)
{
arrays.Add(arr.Skip(skip).Take(take).ToArray());
skip = i + 1;
take = 0;
continue;
}
if (arr[i] != element)
take++;
if (take == 0)
skip = i + 1;
if (arr.Length - 1 == i && take != 0)
arrays.Add(arr.Skip(skip).Take(take).ToArray());
}
return arrays.ToArray();
}
这个可以用(我认为),但是很乱,我不喜欢。
还有其他解决方案吗?
一般情况下,您可以按照以下方式实现它(String.Split
类似例程,但适用于IEnumerable<T>
):
public static IEnumerable<T[]> Split<T>(IEnumerable<T> source,
T delimiter,
StringSplitOptions options = StringSplitOptions.None,
IEqualityComparer<T> comparer = null) {
if (null == source)
yield break; // Or throw new ArgumentNullException(nameof(source));
if (null == comparer)
comparer = EqualityComparer<T>.Default;
List<T> current = new List<T>();
foreach (T item in source) {
if (comparer.Equals(item, delimiter)) {
if (current.Count > 0 || !options.HasFlag(StringSplitOptions.RemoveEmptyEntries))
yield return current.ToArray();
current.Clear();
}
else
current.Add(item);
}
if (current.Count > 0 || !options.HasFlag(StringSplitOptions.RemoveEmptyEntries))
yield return current.ToArray();
}
然后
var arr1 = new int [] { 3, 3, 0, 2, 4, 3, 2 };
var results1 = Split(arr1, 0);
foreach (var arr in results1)
Console.WriteLine(string.Join(", ", arr));
public static IEnumerable<List<TValue>> SplitBy<TValue>(List<TValue> source, TValue by)
{
int start = 0;
int count = 0;
foreach (TValue item in source)
{
if (item.Equals(by))
{
List<TValue> part = source.GetRange(start, count);
start = start + count + 1;
count = 0;
if (part.Any())
{
yield return part;
}
}
else
{
count++;
}
}
List<TValue> rest = source.GetRange(start, count);
yield return rest;
}
https://dotnetfiddle.net/Widget/Preview?url=/Widget/7ORu8p