Kotlin String - indexOf() Function



The Kotlin string indexOf() function is used to return the index of the first occurrence of the specified character or string within this char sequence. This function starts the search from the specified startIndex. If the character or string is not found, it returns -1.

Syntax

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

fun CharSequence.indexOf(char: Char, startIndex: Int = 0, ignoreCase: Boolean = false): Int
fun CharSequence.indexOf(string: String, startIndex: Int = 0, ignoreCase: Boolean = false): Int

Parameters

This function accepts following parameters −

  • Char or String: It represents the char or string to search for within the char sequence.
  • startIndex (optional): This represents the index to start the search with a default value of 0.
  • ignoreCase (optional): If true, the case is ignored during the comparison. Default is false.

Return value

This function returns an index of the first occurrence of a char/string, or -1 if none is found.

Example 1: Index of First Occurrence of String

Following is the basic example of how we can use the indexOf() function to get the first occurrence of a string from this string in Kotlin −

fun main() {
   val CharSequence = "This is Kotlin"
   val search_str = "Kotlin"
   val index = CharSequence.indexOf(search_str, 5)
   println("First occurrence of string is: $index")
}

Output

Following is the output −

First occurrence of string is: 8

Example 2: Index of the First Occurrence of Char

Now, let's look at another example of the indexOf() to get the first occurrence of specified char from this character sequence −

fun main() {
   val CharSequence = "This is Kotlin"
   val search_char = "O"
   val index = CharSequence.lastIndexOf(search_char, 12, ignoreCase=true)
   println("Last occurrence of char is: $index")
}

Output

Following is the output −

Last occurrence of char is: 9

Example 3: If We Check Case Sensitive Char

If we check for case-sensitive characters and ignoreCase is default, this function will return -1 −

fun main() {
   val CharSequence = "This is Kotlin"
   val search_char = "S"
   val index = CharSequence.indexOf(search_char, 2, ignoreCase=false)
   println("First occurrence of char is: $index")
}

Output

Following is the output −

First occurrence of char is: -1
kotlin_strings.htm
Advertisements