- This topic has 3 replies, 3 voices, and was last updated 1 month, 1 week ago by
December 11, 2019 at 3:49 am #192655ModeratorTopics: 3Replies: 169Points: 889Rank: Major Contributor
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.
# 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: 511Points: 1,307Rank: 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: 3Replies: 169Points: 889Rank: Major Contributor
Yeah, you are right, so isn't it a bug?
Like this it is working...
'Hello Hello'.IndexOf('l',7,2) 8
December 11, 2019 at 7:16 pm #192901ParticipantTopics: 10Replies: 1381Points: 1,509Rank: 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
PS C:\WINDOWS\system32> ('Hello Hello').Substring(4,2)
- You must be logged in to reply to this topic.