dotnet / dotnet/dotnet-api-docs
String.LastIndexOf(needle, startIndex) behavior would benefit from some clarification
- Dominant language
- C#
- Stars
- 949
- Forks
- 1.7k
- Avg merge
- 3d 27m
- Merged PRs (30d)
- 49
Description
If we call`"abcabcabc".LastIndexOf("abc", 4)` we might reasonably expect it to return 3, having assessed the character at start index 4 to be 'b' and thus not equal to 'a' of the needle, and moved one position towards the start, where we can find 'a', 'b' and 'c' in indexes 3, 4 and 5 respectively
LastIndexOf actually returns 0, indicating the first match found is the "abc" at the start of the string. A comment in the source code explains the behavior, namely that LastIndexOf() overloads taking a startIndex do not consider characters to the right of the character at startIndex (so for a startIndex of 4, the trailing characters "cabc" are not searched/do not contribute towards finding a match; the search is executed as if the haystack is a Substring terminating after the startIndex character I.e. "abcab")
The current wording of the documentation only states where searching begins and states the direction but I believe it would benefit from an addition that explains the scope of the search doesn't extend to looking for characters to the right of startIndex
Contributor guide
Assessment
This issue has not been assessed yet.