Kotlin String - lastIndexOf() Function



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

Syntax

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

fun CharSequence.lastIndexOf(char: Char, startIndex: Int = lastIndex, ignoreCase: Boolean = false): Int
fun CharSequence.lastIndexOf(string: String, startIndex: Int = lastIndex, 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: Index of character to start the search. The search proceeds backwards towards the beginning of the string..
  • ignoreCase (optional): If true, the case is ignored during the comparison. Default is false.

Return value

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

Example 1: Get the last Occurrence of String

Following is the basic example here, we use the lastIndexOf() to get the last occurrence of the string from the current character sequence in kotlin −

fun main() {
   val CharSequence = "This is Kotlin"
   val search_str = "is "
   val index = CharSequence.lastIndexOf(search_str, 10, ignoreCase=false)
   println("Last occurrence of string is: $index")
}

Output

Following is the output −

Last occurrence of string is: 5

Example 2

Now, let's look at another example of the lastIndexOf() to get the last occurrence of specified char from the given character sequence −

fun main() {
   val string1 = "Kotlin"
   val string2 = "Kotlin "

   // Lexicographical comparison
   println(string1.lastIndexOf(string2)) 
}

Output

Following is the output −

-1

Example 3: Last Index of a Character with Case Sensitivity

In the following example we are retrieving the last index Of a character by setting the ignoreCase to false.

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

Output

Following is the output −

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