Search code examples
c#.netstringframeworkslastindexof

Why does C#'s LastIndexOf behave this way?


I have the following code:

string s = "Hello, World!";
Console.WriteLine(s.LastIndexOf("World"));//7
Console.WriteLine(s.LastIndexOf("World", 7));//-1

Why is the result of the second call to LastIndexOf -1 and not 7?


Solution

  • From MSDN:

    The search begins at the startIndex character position of this instance and proceeds backward toward the beginning until either value is found or the first character position has been examined. For example, if startIndex is Length - 1, the method searches every character from the last character in the string to the beginning.

    Since the search is done backwards, there is no index containing World before 7.