c# - 如何使用特定字符将数组拆分为更小的数组?

标签 c# arrays stringbuilder

如何使用特定字符拆分字符串数组?此示例使用“@”:

string [] stringArray = new string [10];
stringArray[0] = "Hi there, this is page one" //goes into new arrayA
stringArray[1] = "Hi there, this is page two" //goes into new arrayA
stringArray[2] = "Hi there, this is page three" //goes into new arrayA
stringArray[3] = "@" //split
stringArray[4] = "New book, page one" //goes into new arrayB
stringArray[5] = "New book, page two" //goes into new arrayB

最佳答案

您可以编写一个使用SkipTakeWhile 的扩展方法。 此解决方案是通用的,这意味着它适用于您提供的任何类型。请注意,对于引用类型,将进行值比较而不进行引用比较。

public static List<List<T>> Split<T>(this List<T> array, T seperator)
{
    var currentIndex = 0;
    var splitedList = new List<List<T>>();
    while (currentIndex < array.Count)
    {
        var part = array.Skip(currentIndex).TakeWhile(item => !item.Equals(seperator)).ToList();
        splitedList.Add(part);
        currentIndex += part.Count + 1;
    }
    return splitedList;
}

string[] stringArray = new string[6];
stringArray[0] = "Hi there, this is page one"; //goes into new arrayA
stringArray[1] = "Hi there, this is page two"; //goes into new arrayA
stringArray[2] = "Hi there, this is page three"; //goes into new arrayA
stringArray[3] = "@"; //split
stringArray[4] = "New book, page one"; //goes into new arrayB
stringArray[5] = "New book, page two"; //goes into new arrayB

var splittedValue = stringArray.ToList().Split("@");

我知道你有一个巨大的列表,你想做一个像拆分这样的流,你可以使用 yield return。这样做的好处是,当读取列表中的下一项时,代码只会执行到下一个 yield return 语句。

public static IEnumerable<IList<T>> Split<T>(this IEnumerable<T> collection, T seperator)
{
    var items = new List<T>();
    foreach (var item in collection)
    {
        if (item.Equals(seperator))
        {
            yield return items;
            items = new List<T>();
        }
        else items.Add(item);
    }
    yield return items;
}

关于c# - 如何使用特定字符将数组拆分为更小的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44655001/

相关文章:

c# - ASP 固定 header

javascript - fs.createReadStream 之后代码块未执行

java - 如何倒序获取输入流的内容?

c# - 如何在不同的 CPU 内核上生成线程?

c# - 如何在 C# 中对开放类型进行泛型多态?

c# - 如何为自定义创建的类获取智能感知?

java - Jackson 中的序列化数组类型和数组

ruby - 如何在 Ruby 中创建哈希数组

java - 为什么通过 List<String> 进行迭代比拆分字符串和通过 StringBuilder 进行迭代慢?

java - StringBuilder 和 ResultSet 性能问题的可能原因是什么