'IndexOf' method of String, is it malfunctioning or expected behaviour?

Hello mates,

As per the Microsoft Docs, it says zero-based index and starts at a specified char position, any idea why few statements are failing below…

IndexOf(Char, Int32, Int32)

Reports the zero-based index of the first occurrence of the specified character in this instance. The search starts at a specified character position and examines a specified number of character positions.

[pre] # One of the syntaxs of IndexOf # int IndexOf(char value, int startIndex, int count)

‘Hello Hello’.IndexOf(‘l’,0,2)
-1 # Failed

‘Hello Hello’.IndexOf(‘l’,1,2)
2 # Found the match

‘Hello Hello’.IndexOf(‘l’,4,2)
-1 # Failed
[/pre]

Any idea??

Thank you.

The key is in the statement you quoted:

The search starts at a specified character position and examines a specified number of character positions.
In other words, it will search starting at whatever numbered index, and it will "give up" if it hasn't found it after looking at that number of consecutive characters. :)

Yeah, you are right, so isn’t it a bug?

Like this it is working…

[pre]‘Hello Hello’.IndexOf(‘l’,7,2)
8 [/pre]

Thank you.

'Hello Hello'.IndexOf('l',4,2)

As Joel is explaining, try speaking the logic in plain text. Look in the string ‘Hello Hello’, start at character 4 (e.g. Hello Hello) and search the next 2 characters (e.g. o ) for a l. A visual example, string and associated index:

H|e|l|l|o| |H|e|l|l|o
0|1|2|3|4|5|6|7|8|9|10

Edit: Lines up nice in the editor, but the font in the forum isn’t monospace

Another example:

PS C:\WINDOWS\system32> ('Hello Hello').Substring(4,2)