indexof()

报告输入字符串中指定的字符串第一次出现时的索引(从零开始)。

有关详细信息,请参阅 indexof_regex()

语法

indexof(string,match[,start[,length[,occurrence]]])

详细了解语法约定

参数

客户 类型​​ 必需 说明
字符串 string 要搜索的源字符串。
match string 要搜索的字符串。
start int 搜索开始位置。 如果是负值,则将从 string 的末尾起,将起始搜索位置偏移以下步数:abs(start)
length int 要检查的字符位置数。 值为 -1 表示长度没有限制。
occurrence int 出现的次数。 默认值为 1。

注意

如果 string 或 match 不属于 string 类型,则此函数会将其值强制转换为 string

返回

match 的索引位置(从零开始)。

  • 如果在 string 中找不到 match,则返回 -1。
  • 如果符合以下条件,则返回 null
    • start 小于 0。
    • occurrence 小于 0。
    • length 小于 -1。

示例

print
 idx1 = indexof("abcdefg","cde")    // lookup found in input string
 , idx2 = indexof("abcdefg","cde",1,4) // lookup found in researched range 
 , idx3 = indexof("abcdefg","cde",1,2) // search starts from index 1, but stops after 2 chars, so full lookup can't be found
 , idx4 = indexof("abcdefg","cde",3,4) // search starts after occurrence of lookup
 , idx5 = indexof("abcdefg","cde",-5)  // negative start index
 , idx6 = indexof(1234567,5,1,4)       // two first parameters were forcibly casted to strings "12345" and "5"
 , idx7 = indexof("abcdefg","cde",2,-1)  // lookup found in input string
 , idx8 = indexof("abcdefgabcdefg", "cde", 1, 10, 2)   // lookup found in input range
 , idx9 = indexof("abcdefgabcdefg", "cde", 1, -1, 3)   // the third occurrence of lookup is not in researched range

输出

idx1 idx2 idx3 idx4 idx5 idx6 idx7 idx8 idx9
2 2 -1 -1 2 4 2 9 -1