Skip to content

INSTR

来源: https://www.freebasic.net/wiki/wikka.php?wakka=KeyPgInstr 最后更新: 2025-08-29

在字符串中定位子字符串或字符的第一次出现位置。

语法

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

用法:

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

参数

  • str — 要搜索的字符串。
  • substring — 要查找的子字符串。
  • start — 搜索开始的位置(在 str 中)。第一个字符的位置为 1。

返回值

substringstr 中第一次出现的位置。

说明

定位子字符串或字符在字符串中的第一次出现位置。

  • 不提供 start 时:从第一个字符开始搜索。
  • 以下情况返回 0
    • 未找到 substring
    • strsubstring 为空字符串
    • start < 1

若指定了 Any 关键字,Instr 返回 substring任意字符的第一次出现位置。

示例

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

平台差异

  • DOS 目标不支持 Instr 的宽字符字符串版本。

与 QB 的差异

  • QB 在 search 为零长度字符串时返回 start
  • QB 不支持 Unicode。

另请参阅

基于 FreeBASIC 官方文档翻译 如有侵权请联系我们删除
FreeBASIC 是开源项目,与微软公司无隶属关系