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