I have the following code:
string s = "Hello, World!";
Console.WriteLine(s.LastIndexOf("World"));//7
Console.WriteLine(s.LastIndexOf("World", 7));//-1
Why the result of the second call to LastIndexOf is -1 and not 7?
I have the following code:
string s = "Hello, World!";
Console.WriteLine(s.LastIndexOf("World"));//7
Console.WriteLine(s.LastIndexOf("World", 7));//-1
Why the result of the second call to LastIndexOf is -1 and not 7?
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.
If you take a look at the doc of LastIndexOf Method (Char, Int32):
return The zero-based index position of value if that character is found, or -1 if it is not found or if the current instance equals String.Empty.
Since 7 seems to be the last index, what's after this position is empty, thus the return value is -1
The search starts at a specified character position and proceeds backward toward the beginning of the string as doc says.
In your case there is no occurrence of word "World" in range 0 - 7 "Hello, W"