string.LastIndexOf() Bug?

Florian Gl picture Florian Gl · Sep 14, 2012 · Viewed 14.9k times · Source

does anyone know why:

"  <exception>".LastIndexOf("<",0) returns -1 (wrong)

while

"  <exception>".LastIndexOf("<") returns 2 (right)

and

"<exception>".LastIndexOf("<",0) returns 0 (right)

Is this a bug or am I misunderstanding the LastIndexOf-Method?

Answer

O. R. Mapper picture O. R. Mapper · Sep 14, 2012

You are misunderstanding that particular overload of the LastIndexOf method.

The docs state the following:

The search starts at a specified character position and proceeds backward toward the beginning of the string.

Note that it says backward. So, if you start at position 0, there is no "<" substring at that position or in front of that position and hence the result is -1.

In contrast, if you use the overload that takes only the substring, the search will start at the end of the string and hence correctly find the indicated substring.