ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

SplitNext

Split the next part of this span with the given separator

Source

public static class Extensions {

    /// <summary>
    /// Split the next part of this span with the given separator. 
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="span">A reference to the span</param>
    /// <param name="seperator">A seperator that delimits the values</param>
    /// <returns>The first splitted value</returns>
    public static ReadOnlySpan<T> SplitNext<T>(this ref ReadOnlySpan<T> span, T seperator) where T : IEquatable<T> {
        int pos = span.IndexOf(seperator);
        if (pos > -1) {
            var part = span.Slice(0, pos);
            span = span.Slice(pos + 1);
            return part;
        } else {
            var part = span;
            span = span.Slice(span.Length);
            return part;
        }
    }

}

Example

var span = "123,456,7890".AsSpan();

Console.WriteLine(span.SplitNext(',').ToString()); // 123
Console.WriteLine(span.SplitNext(',').ToString()); // 456
Console.WriteLine(span.SplitNext(',').ToString()); // 7890

Author: Fons Sonnemans

Submitted on: 8 jun. 2018

Language: C#

Type: ReadOnlySpan

Views: 4662