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

Welcome Forums General PowerShell Q&A 'IndexOf' method of String, is it malfunctioning or expected behaviour?

Viewing 3 reply threads
  • Author
    Posts
    • #192655
      Moderator
      Topics: 3
      Replies: 169
      Points: 889
      Helping Hand
      Rank: Major Contributor

      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.

      # 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
      

      Any idea??

      Thank you.

    • #192658
      Participant
      Topics: 2
      Replies: 511
      Points: 1,307
      Helping Hand
      Rank: 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. 🙂

    • #192682
      Moderator
      Topics: 3
      Replies: 169
      Points: 889
      Helping Hand
      Rank: Major Contributor

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

      Like this it is working...

      'Hello Hello'.IndexOf('l',7,2)
      8 

      Thank you.

    • #192901
      Participant
      Topics: 10
      Replies: 1381
      Points: 1,509
      Helping Hand
      Rank: Community Hero

      '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)
      
Viewing 3 reply threads
  • You must be logged in to reply to this topic.