How do I divide an array into small arrays using a specific character?

advertisements

How do I split an array of strings using a specific character? this example using '@':

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


You could write an extension method which makes use of Skip and TakeWhile. This solution is generic which means it will work with any type you give it. Just be aware that for reference types a value comparison and no reference comparison will be done.

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("@");

I've you have a huge list and you want to do a stream like split you can use a yield return. The advantage of it is that when the next item in the list is read the code will only be executed to the next yield return statement.

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;
}