Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string.Split for Span?

Tags:

c#

.net

I was wondering how I may implement, or whether or not there are any workarounds, for a sring.Split() method, but for ReadOnlySpan<T> or Span in C#, because unfortunately ReadOnlySpan<T>.Split() does not seem to exist.

I am not quite sure how to achieve the behaviour I wish for. It probably could be implemented by leveraging the combined power of ReadOnlySpan<T>.IndexOf() and ReadOnlySpan<T>.Slice(), but because even the support for ReadOnlySpan<T>.IndexOf() isn't too great (it isn't possible to specify a startIndex or a Count), I would prefer to avoid this entirely.

I am also aware that the problem with a ReadOnlySpan<T>.Split() method would be, that it isn't possible to return ReadOnlySpan<T>[] or ReadOnlySpan<ReadOnlySpan<T>>, because it is a ref struct and therefore must be stack-allocated, and putting it into any collection would require a heap allocation.

So has anyone any idea, on how I may achieve that?

Edit: It should work, without knowing the amount of parts returned beforehand....


1 Answers

.NET 9 introduces a built-in means to split spans without allocation.

var span = "name,rank,serial".AsSpan();

foreach(var chunk in span.Split(','))
{
    if(span[chunk].SequenceEquals("name"))
        Console.WriteLine("The string contains `name`");
}

Documentation: https://learn.microsoft.com/en-us/dotnet/core/whats-new/dotnet-9/libraries#enumerate-over-readonlyspancharsplit-segments

like image 168
Charles Burns Avatar answered Jan 01 '26 23:01

Charles Burns