- This topic has 3 replies, 3 voices, and was last updated 9 months, 1 week ago by
December 11, 2019 at 3:49 am #192655ModeratorTopics: 5Replies: 237Points: 1,320Rank: Community Hero
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.PowerShell1234567891011# 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
December 11, 2019 at 4:27 am #192658ParticipantTopics: 2Replies: 513Points: 1,322Rank: Community Hero
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. 🙂
December 11, 2019 at 7:14 am #192682ModeratorTopics: 5Replies: 237Points: 1,320Rank: Community Hero
Yeah, you are right, so isn’t it a bug?
Like this it is working…PowerShell12‘Hello Hello’.IndexOf(‘l’,7,2)8
December 11, 2019 at 7:16 pm #192901ParticipantTopics: 13Replies: 1753Points: 3,136Rank: Community Hero
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:
Edit: Lines up nice in the editor, but the font in the forum isn’t monospace
Another example:PowerShell1PS C:\WINDOWS\system32> ('Hello Hello').Substring(4,2)
- The topic ‘‘IndexOf’ method of String, is it malfunctioning or expected behaviour?’ is closed to new replies.