Skip to content

INSTR

Source: https://www.freebasic.net/wiki/wikka.php?wakka=KeyPgInstr Last revised: 2025-08-29

Locates the first occurrence of a substring or character within a string.

Syntax

declare function Instr ( byref str as const string, [Any] byref substring as const string ) as integer
declare function Instr ( byref str as const wstring, [Any] byref substring as const wstring ) as integer
declare function Instr ( byval start as integer, byref str as const string, [Any] byref substring as const string ) as integer
declare function Instr ( byval start as integer, byref str as const wstring, [Any] byref substring as const wstring ) as integer

Usage:

first = Instr( [start,] str, [Any] substring )

Parameters

  • str — The string where to search.
  • substring — The substring to find.
  • start — The position in str at which the search begins. First character is at position 1.

Return Value

The position of the first occurrence of substring in str.

Description

Locates the position of the first occurrence of a substring or character within a string.

  • Without start: search begins at the first character.
  • Returns 0 if:
    • substring is not found
    • str or substring are empty strings
    • start < 1

If the Any keyword is specified, Instr returns the first occurrence of any character in substring.

Examples

vb
' It will return 4
Print InStr("abcdefg", "de")

' It will return 0
Print InStr("abcdefg", "h")

' Search for any of the characters "f", "b", "c" — returns 2 as "b" is first
Print InStr("abcdefg", Any "fbc")

Dim test As String
Dim idx As Integer
test = "abababab"
idx = InStr(test, "b")
Do While idx > 0
    Print """b"" at " & idx
    idx = InStr(idx + 1, Test, "b")
Loop

' Unicode example:
Dim text As WString * 20
text = "Привет, мир!"
Print InStr(text, "ет")  ' displays 5

Platform Differences

  • The wide-character string version of Instr is not supported for DOS target.

Differences from QB

  • QB returns start if search is a zero-length string.
  • QB does not support Unicode.

See Also

Translated from FreeBASIC official docs. Contact us for removal if infringed.
FreeBASIC is an open-source project, not affiliated with Microsoft