Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do String.IndexOf(string) and ReadOnlySpan.IndexOf(string) return different values

Tags:

c#

In the below code, the string.IndexOf() returns a positive integer indicating success. The span version returns -1, indicating failure. Why is this.

string str = "Something Something Something myvalue";

ReadOnlySpan<string> span = new(str);

var indexWithString = str.IndexOf(@"myvalue");

var indexWithSpan = span.IndexOf(@"myvalue");

The same holds for Contains().

like image 648
Alessandro Rizzi Avatar asked Oct 26 '25 09:10

Alessandro Rizzi


1 Answers

Non-compiling example code aside, it appears to fail because ReadOnlySpan<string> is not a string. It's a collection of strings. You're not searching for the index of the text within the string you put in the span, but rather the index of the whole string. Try the below code to see this behavior:

string str = "Something Something Something myvalue";

ReadOnlySpan<string> span = new(str);

var indexWithString = str.IndexOf(@"myvalue");
Console.WriteLine(indexWithString); // Outputs 30

var indexWithSpan = span.IndexOf(@"myvalue");
Console.WriteLine(indexWithSpan); // Outputs -1

var indexCheat = span.IndexOf(str);
Console.WriteLine(indexCheat); // Outputs 0, because it matches the string in first place of this span.
like image 75
Logarr Avatar answered Oct 29 '25 07:10

Logarr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!