2023-10-30

string.Split for Span?

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....



No comments:

Post a Comment