Skip to content

String.LastIndexOf(needle, startIndex) behavior would benefit from some clarification  #7751

Open
@CaiusJard

Description

@CaiusJard

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions