How would an implementation of a SubstringFromStart
method look like when Span<T>
should be leveraged? Assuming substringLength <= input.Length
:
ReadOnlySpan<char> span = input.AsSpan().Slice(0, substringLength);
return new string(span.ToArray());
Is this the way to go? Is there a better, more concise way than new string(span.ToArray())
?
Is this the way to go?
No, using Span<T>
is useless here, since you need a character array for the string constructor (there is none that accepts a Span<char>
yet).
You would benefit using Span<T>
here if:
Span<char>
, rather than a string
. Then you wouldn't need the string allocation;Span<char>
as input and you never need to materialize it to an array, or you wouldn't need a intermediate materialization (when passing it into the method for example).If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With