Kotlin String - substring() Function



The Kotlin string substring() function returns a substring or sequence of characters of the current string that starts at the specified startIndex and continues to the end of the string, or ends right before the specified endIndex if provided.

startIndex is mandatory for this function; if we do not pass it, an error will be thrown. If we pass either startIndex or endIndex, it will be considered as startIndex only.

Syntax

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

fun String.substring(startIndex: Int): String
fun String.substring(startIndex: Int, endIndex: Int): String

Parameters

This function accepts following parameters −

  • startIndex: It represents the starting position of the substring. The substring includes characters at this index.
  • endIndex (optional): It represents the ending position of the substring (exclusive). If not provided substring continues to the end of the string.

Return value

This function returns a string.

Example 1: Return a Substring From this String

Following is the basic example, we use the substring() to return a substring from this string −

fun main() {
   val str = "This is kotlin"
   val substring = str.substring(6, 12)
   println("substring: $substring")
}

Output

Following is the output −

substring: s kotl

Example 2: If We do not Pass EndIndex

If we do not provide endIndex, the substring starts from the specified startIndex and continues till the end

fun main() {
   val str = "This is tutorialspoint!"
   val substring = str.substring(5)
   println("substring: $substring")
}

Output

Following is the Output −

substring: is tutorialspoint!

Example 3: If we do not pass startIndex

If we do not pass startIndex and pass only endIndex then endIndex is treated as startIndex, because startIndex is mandatory −

fun main() {
   val input = "Understanding kotlin Substring Functionality"
   // Extract substring with startIndex and endIndex
   // val startIndex = 10
   val endIndex = 20
   val substringWithEnd = input.substring(endIndex)
   println("Substring with endIndex only:" + substringWithEnd)
}

Output

Following is the Output −

Substring with endIndex only: Substring Functionality
kotlin_strings.htm
Advertisements