indexof()indexof()

报告输入字符串中指定的字符串第一次出现时的索引(从零开始)。Reports the zero-based index of the first occurrence of a specified string within the input string.

如果查找或输入字符串不是字符串类型,此函数会强制将值转换为字符串。If lookup or input string isn't of string type, the function forcibly casts the value to string .

有关详细信息,请参阅 indexof_regex()For more information, see indexof_regex().

语法Syntax

indexof(source,lookup[,start_index[,length[,occurrence]]])indexof(source,lookup[,start_index[,length[,occurrence]]])

参数Arguments

  • source :输入字符串。source : Input string.
  • lookup:要查找的字符串。lookup : String to look up.
  • start_index:搜索开始位置。start_index : Search start position. 可选。Optional.
  • length :要检查的字符位置数。length : Number of character positions to examine. 值为 -1 表示长度没有限制。A value of -1 means unlimited length. 可选。Optional.
  • occurrence:出现的次数。occurrence : The number of the occurrence. 默认值 1。Default 1. 可选。Optional.

返回Returns

查找的从零开始的索引位置。Zero-based index position of lookup .

如果在输入中找不到该字符串,则返回 -1。Returns -1 if the string isn't found in the input.

如果是不相关(小于 0)的 start_index、occurrence 或(小于 -1)length 参数,则返回 null。If irrelevant (less than 0) start_index , occurrence , or (less than -1) length parameter - returns null .

示例Examples

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",-1)  // invalid input
 , 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
idx1idx1 idx2idx2 idx3idx3 idx4idx4 idx5idx5 idx6idx6 idx7idx7 idx8idx8 idx9idx9
22 22 -1-1 -1-1 44 22 99 -1-1