Skip to main content

How to find the index of a specific character or substring in a string in Kotlin

How to find the index of a specific character or substring in a string in Kotlin.

Here's a step-by-step tutorial on how to find the index of a specific character or substring in a string in Kotlin.

Finding the index of a specific character

To find the index of a specific character in a string, you can use the indexOf() function. This function returns the index of the first occurrence of the specified character in the string.

Here's an example:

val str = "Hello, World!"
val ch = 'o'

val index = str.indexOf(ch)
println("The index of '$ch' in '$str' is $index") // Output: The index of 'o' in 'Hello, World!' is 4

In this example, we have a string str and a character ch. We call the indexOf() function on str and pass ch as the argument. The function returns the index of the first occurrence of ch in str, which is 4.

Finding the index of a specific substring

To find the index of a specific substring in a string, you can use the indexOf() function with an additional parameter. This parameter specifies the starting index from where the search for the substring should begin.

Here's an example:

val str = "Hello, World!"
val substr = "World"

val index = str.indexOf(substr)
println("The index of '$substr' in '$str' is $index") // Output: The index of 'World' in 'Hello, World!' is 7

In this example, we have a string str and a substring substr. We call the indexOf() function on str and pass substr as the argument. The function returns the index of the first occurrence of substr in str, which is 7.

Finding the index of the last occurrence

If you want to find the index of the last occurrence of a character or substring in a string, you can use the lastIndexOf() function instead of indexOf().

Here's an example:

val str = "Hello, World!"
val ch = 'o'

val index = str.lastIndexOf(ch)
println("The index of last '$ch' in '$str' is $index") // Output: The index of last 'o' in 'Hello, World!' is 8

In this example, we use the lastIndexOf() function to find the index of the last occurrence of the character 'o' in the string str, which is 8.

Handling non-existent characters or substrings

If the character or substring you're searching for doesn't exist in the string, the indexOf() and lastIndexOf() functions will return -1.

Here's an example:

val str = "Hello, World!"
val ch = 'x'

val index = str.indexOf(ch)
println("The index of '$ch' in '$str' is $index") // Output: The index of 'x' in 'Hello, World!' is -1

In this example, the character 'x' doesn't exist in the string str, so the indexOf() function returns -1.

That's it! You now know how to find the index of a specific character or substring in a string in Kotlin.