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 第一次出現的索引,如果沒有找到。