为什么 C# 的 LastIndexOf 会这样?

Why is C#'s LastIndexOf behave this way?

我有以下代码:

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

为什么第二次调用 LastIndexOf 的结果是 -1 而不是 7?

如果你看一下 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.

因为7好像是最后一个索引,这个位置后面是空的,所以return的值为-1

来自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.

由于是向后查找,所以在7之前没有包含World的索引。

搜索从指定的字符位置开始,然后按照文档所述向后搜索字符串的开头。

在你的情况下,在 0 - 7 "Hello, W"

范围内没有出现单词 "World"