如何使用特定字符拆分字符串数组?此示例使用“@”:
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
最佳答案
您可以编写一个使用Skip
和TakeWhile
的扩展方法。
此解决方案是通用的,这意味着它适用于您提供的任何类型。请注意,对于引用类型,将进行值比较而不进行引用比较。
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/