Mid versus IndexOf

Here’s the logic I used to convince Geoff that Middle should be 0-based. It was originally 1-based in the first API2 versions.

If I’m trying to parse something like Var Target As String = "Key=Value", I can use Var KeyLen As Integer = Target.IndexOf("=") which gives me 3. This is conveniently also the number of characters I need to skip to find the equal sign. And what does Left need? A number of characters. So I can do Var LeftPart As String = Target.Left(KeyLen). Now to get the right side, I just need Middle, plus one character to skip the equals sign: Var RightPart As String = Target.Middle(KeyLen + 1).

This all works really nicely in your head, which is important.

Mid and InStr weren’t exactly hard to figure out, but they are absolutely less intuitive.

Var Target As String = "Key=Value"
Var EqualsPosition As Integer = InStr(Target, "=")
Var LeftPart As Integer = Left(Target, EqualsPosition - 1)
Var RightPart As Integer = Mid(Target, EqualsPosition)

Even after 20 years of writing Xojo code, this feels really weird. It feels like the position is after the equals sign. That I have to go backwards to find the chunk before it.

Essentially, IndexOf is “how many characters did you skip to find the one being searched for.” That sounds right to me. Left and Right skip a certain number of characters too. Why wouldn’t Middle work the same way?

2 Likes