‘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: 5
      Replies: 237
      Points: 1,320
      Helping Hand
      Rank: Community Hero

      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.

      Any idea??

      Thank you.

    • #192658
      Participant
      Topics: 2
      Replies: 513
      Points: 1,322
      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: 5
      Replies: 237
      Points: 1,320
      Helping Hand
      Rank: Community Hero

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

      Like this it is working…

      Thank you.

    • #192901
      Participant
      Topics: 13
      Replies: 1753
      Points: 3,136
      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:

Viewing 3 reply threads
  • The topic ‘‘IndexOf’ method of String, is it malfunctioning or expected behaviour?’ is closed to new replies.