In this tutorial, you shall learn how to get the index of a specific search string in a given string in Kotlin, using String.indexOf() function, with examples.
Kotlin – Index of Substring in String
To find index of substring in this string in Kotlin, call indexOf() method on this string, and pass the substring as argument.
String.indexOf() returns an integer representing the index of first occurrence of the match for the given substring. If there is no match found for the given substring, then indexOf() returns -1
.
Syntax
The syntax of indexOf() method is
fun CharSequence.indexOf(
string: String,
startIndex: Int = 0,
ignoreCase: Boolean = false
): Int
Examples
1. Find index of substring “apple”
In the following example, we take a string in str
and find the index of the substring "apple"
in str
string.
Main.kt
fun main(args: Array<String>) {
var str = "an apple a day. Some apples is red."
val index = str.indexOf("apple")
println("Index : $index")
}
Output
Index : 3
2. Find index of substring with search from a specific start
We can also provide an optional start index for second argument. The search for the substring in this string happens from this start index.
In the following example, we find the index of the substring "apple"
in the string str
from the start index 8
.
Main.kt
fun main(args: Array<String>) {
var str = "an apple a day. Some apples is red."
val index = str.indexOf("apple", startIndex = 8)
println("Index : $index")
}
Output
Index : 21
Since we are searching from start index 8
, the first occurrence of the given substring is ignored.
3. Find index of substring with search ignoring case
We can also try to find the match by ignoring the case.
In the following example, we find the index of the substring "APPLE"
in the string str
.
Main.kt
fun main(args: Array<String>) {
var str = "an apple a day. Some apples is red."
val index = str.indexOf("APPLE", ignoreCase = true)
println("Index : $index")
}
Output
Index : 3
4. Find index of substring – Negative Scenario
Now, let us take a substring which is not present in the string, and find the index returned by indexOf() method.
Main.kt
fun main(args: Array<String>) {
var str = "an apple a day. Some apples is red."
val index = str.indexOf("mango")
println("Index : $index")
}
Output
Index : -1
Conclusion
In this Kotlin Tutorial, we learned how to find the index of a substring in the given string using String.indexOf(), with examples.