【问题标题】:C# - Split Array by Another ArrayC# - 由另一个数组拆分数组
【发布时间】:2021-08-03 22:23:43
【问题描述】:

我有一个字符串数组,我想被另一个数组分割(第二个数组中的每个项目)。

string[] array1 = { "item1", "item2", "item3", "item4", "item5" ,"item6" };
string[] array2 = { "item2", "item5" };

结果为@​​987654322@

results[0] = { "item1" }  
results[1] = { "item2", "item3", "item4" }  
results[2] = { "item5", "item6" }

还有应该在下一个数组之前添加拆分的项目。例如。 item2 拆分 results[0] 和 results[1] 并在 result[1] 前面使用。
提示: 可能类似于使用 IndexOf()Insert()for 循环函数中

我已经用字符串试过了。但我不知道如何处理数组。

string str = "item1,item2,item3,item4,item5,item6";
string[] array = str.Split(new string[] { "item2","item5" }, StringSplitOptions.None);

我尝试在 google 中找到这个问题,但到目前为止还没有找到。只有我发现了如何拆分成块(意思是每个数组中的项目数)而不是另一个项目(尤其是多个项目)。

【问题讨论】:

  • 你能解释清楚吗?
  • 我需要按字符串拆分数组
  • “在第二个数组中指定的值处拆分数组”怎么样。这可能是一种更准确的表述方式。
  • "split Array by string" 并不比你已经说过的好。此外,如果您澄清您的问题,请编辑它,不要使用评论部分。
  • 另外,拆分集合中的顺序是否重要?例如,两个集合都是有序的吗?如果item5 出现在item2 之前怎么办?必须先在items2 上拆分吗?

标签: c# arrays list split


【解决方案1】:

所以您想要一种“拆分”方法,通过在第二个集合中提供拆分索引将一个集合拆分为多个?您可以使用以下扩展方法,该方法使用 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);

【讨论】:

  • 谢谢蒂姆·施梅尔特。这正是我所需要的。事实上,它超出了我的预期。因为它适用于列表和数组。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-28
  • 1970-01-01
  • 1970-01-01
  • 2018-11-09
  • 2022-10-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多