indexOf所在位置是kotlin.text.indexOf,其相关用法介绍如下。

用法一

fun CharSequence.indexOf(
    char: Char, 
    startIndex: Int = 0, 
    ignoreCase: Boolean = false
): Int

返回此字符串中第一次出现指定字符的索引,从指定的 startIndex 开始。

参数

ignoreCase-true匹配字符时忽略字符大小写。默认false.

返回 char 第一次出现的索引,如果没有找到,则返回 -1。

用法二

fun CharSequence.indexOf(
    string: String, 
    startIndex: Int = 0, 
    ignoreCase: Boolean = false
): Int

从指定的 startIndex 开始,返回指定 string 首次出现在此字符序列中的索引。

例子:

import java.util.Locale
import kotlin.test.*

fun main(args: Array<String>) {
//sampleStart
fun matchDetails(inputString: String, whatToFind: String, startIndex: Int = 0): String {
    val matchIndex = inputString.indexOf(whatToFind, startIndex)
    return "Searching for '$whatToFind' in '$inputString' starting at position $startIndex: " +
            if (matchIndex >= 0) "Found at $matchIndex" else "Not found"
}

val inputString = "Never ever give up"
val toFind = "ever"

println(matchDetails(inputString, toFind)) // Searching for 'ever' in 'Never ever give up' starting at position 0: Found at 1
println(matchDetails(inputString, toFind, 2)) // Searching for 'ever' in 'Never ever give up' starting at position 2: Found at 6
println(matchDetails(inputString, toFind, 10)) // Searching for 'ever' in 'Never ever give up' starting at position 10: Not found
//sampleEnd
}

输出:

Searching for 'ever' in 'Never ever give up' starting at position 0: Found at 1
Searching for 'ever' in 'Never ever give up' starting at position 2: Found at 6
Searching for 'ever' in 'Never ever give up' starting at position 10: Not found

参数

ignoreCase-true匹配字符串时忽略字符大小写。默认false.

返回 string-1 第一次出现的索引,如果没有找到。