[英]C# - Split Array by Another Array
我有一個字符串數組,我想被另一個數組分割(由第二個數組中的每個項目)。
string[] array1 = { "item1", "item2", "item3", "item4", "item5" ,"item6" };
string[] array2 = { "item2", "item5" };
結果為string[][] or List<string[]>
results[0] = { "item1" }
results[1] = { "item2", "item3", "item4" }
results[2] = { "item5", "item6" }
還有應該在下一個數組之前添加拆分的項目。 例如。 item2 拆分 results[0] 和 results[1] 並在 result[1] 前面使用。
提示:可能類似於在for
循環 function 中使用IndexOf()
或Insert()
我用字符串試過這個。 但我不知道如何處理數組。
string str = "item1,item2,item3,item4,item5,item6";
string[] array = str.Split(new string[] { "item2","item5" }, StringSplitOptions.None);
我試圖在谷歌中找到這個問題,但到目前為止還沒有找到。 只有我發現如何拆分成塊(意思是每個數組中的項目數)而不是另一個項目(特別是多個項目)。
所以你想要一種“拆分”方法,通過在第二個集合中提供拆分索引將一個集合拆分為多個? 您可以使用以下擴展方法,該方法將Queue<T>
( FIFO ) 用於拆分項目。 它非常靈活,您可以將它與每種類型一起使用,並且您可以選擇提供比較器。 例如,如果您想以不區分大小寫的方式進行比較,請提供StringComparer.CurrentCultureIgnoreCase
:
public static class EnumerableExtensions
{
public static IList<IList<T>> SplitOnItems<T>(this IEnumerable<T> seqeuenceToSplit, IEnumerable<T> splitOnItems, IEqualityComparer<T> comparer = null)
{
if(comparer == null) comparer = EqualityComparer<T>.Default;
Queue<T> queue = new Queue<T>(splitOnItems);
if(queue.Count == 0)
{
return new IList<T>[]{new List<T>(seqeuenceToSplit)};
}
T nextSplitOnItem = queue.Dequeue();
List<T> nextBatch = new List<T>();
IList<IList<T>> resultList = new List<IList<T>>();
bool takeRemaining = false;
foreach(T item in seqeuenceToSplit)
{
if(!takeRemaining && comparer.Equals(item, nextSplitOnItem))
{
resultList.Add(nextBatch);
nextBatch = new List<T> { item };
if (queue.Count > 0)
{
nextSplitOnItem = queue.Dequeue();
}
else
{
takeRemaining = true;
}
}
else
{
nextBatch.Add(item);
}
}
if(nextBatch.Any())
resultList.Add(nextBatch);
return resultList;
}
}
用法:
string[] array1 = { "item1", "item2", "item3", "item4", "item5" ,"item6" };
string[] array2 = { "item2", "item5" };
IList<IList<string>> splittedItems = array1.SplitOnItems(array2);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.