How to Find Index of Character in String Kotlin
In Kotlin, use the
indexOf() function on a string to find the index of a character. It returns the first position of the character or -1 if not found.Syntax
The indexOf() function is called on a string and takes a character as an argument. It returns an integer representing the first index where the character appears, or -1 if the character is not found.
string.indexOf(char): Finds the first occurrence ofchar.- Returns
Int: index position starting at 0, or-1if missing.
kotlin
val text = "hello" val index = text.indexOf('e')
Example
This example shows how to find the index of a character in a string and handle the case when the character is not found.
kotlin
fun main() {
val word = "kotlin"
val charToFind = 't'
val index = word.indexOf(charToFind)
if (index != -1) {
println("Character '$charToFind' found at index: $index")
} else {
println("Character '$charToFind' not found in the string.")
}
}Output
Character 't' found at index: 2
Common Pitfalls
One common mistake is expecting indexOf() to return null if the character is not found, but it actually returns -1. Always check for -1 before using the index.
Another pitfall is confusing character 'a' with string "a". indexOf() for characters requires a Char argument, not a String.
kotlin
fun main() {
val text = "apple"
// Wrong: passing String instead of Char
// val wrongIndex = text.indexOf("a") // This causes a compile error
// Correct:
val correctIndex = text.indexOf('a')
println(correctIndex) // Output: 0
// Checking for character not found
val missingIndex = text.indexOf('z')
if (missingIndex == -1) {
println("Character not found")
}
}Output
0
Character not found
Quick Reference
| Function | Description | Returns |
|---|---|---|
| indexOf(char) | Finds first index of character | Int index or -1 if not found |
| indexOf(char, startIndex) | Finds first index of character starting from startIndex | Int index or -1 |
| lastIndexOf(char) | Finds last index of character | Int index or -1 |
Key Takeaways
Use
indexOf() to find the first position of a character in a Kotlin string.The function returns
-1 if the character is not found, not null.Pass a
Char (single quotes) to indexOf(), not a String.Check the returned index before using it to avoid errors.
You can also use
lastIndexOf() to find the last occurrence of a character.