Kotlin String - indexOfFirst() Function



The Kotlin string indexOfFirst() function is used to return index of the first character matching the given predicate, or -1 if the char sequence does not contain such character.

This function is useful for finding the first uppercase letter in a string, finding the first digit in a sequence, and identifying the first non-alphanumeric character in a string.

Syntax

Following is the syntax of the Kotlin string indexOfFirst() function −

fun CharSequence.indexOfFirst(
   predicate: (Char) -> Boolean
): Int

Parameters

This function accepts a predicate representing the lambda function that defines the condition to match. It is applied to each character in the string until the condition is satisfied.

Return value

This function returns an index of the first character matching the predicate, or -1 if the string does not contain such a character.

Example 1: Get Index of First Char

Following is the basic example, we use indexOfFirst() to get the index of the first char matching the predicate in kotlin −

fun main() {
   val str = "This is kotlin"
   val index = str.indexOfFirst { it in "aeiou" }
   println("index of the first vowel: $index")
}

Output

Following is the output −

index of the first vowel: 2

Example 2: Get Index of First Digit

Now, let's look at another example of the indexOfFirst() to get the index of the first digit in the string −

fun main() {
   val str = "Hello, sector136"
   val index = str.indexOfFirst { it.isDigit() }
   println("Index of first Digit: $index")
}

Output

Following is the output −

Index of first Digit: 13

Example 3: Get Index of First Uppercase

In this example, we display the index of the first uppercase letter using the indexOfFirst() in Kotlin −

fun main() {
   val str = "hello TutorialsPoint"
   val index = str.indexOfFirst { it.isUpperCase() }
   println("Index of first uppercase: $index")
}

Output

Following is the output −

Index of first uppercase: 6
kotlin_strings.htm
Advertisements