Kotlin String - slice() Function



The Kotlin string slice() function is used to returns a character sequence or string containing characters from the original character sequence or string at the specified range or indices.

The slice() function does not modify the original string it only returns a new string from this string.

Syntax

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

fun String.slice(indices: IntRange): CharSequence
fun String.slice(indices: Iterable<Int>): CharSequence

Parameters

This function accepts following parameters −

  • indices (IntRange): It specifies the range of indices (inclusive) from which character are extracted.
  • indices (Iterable<Int>): It specifies an iterable collection of distinct indices to extract characters from.

Return value

This function returns a charSequence, which can represent either a string or other character sequences.

Example 1: Extract String From This String

Following is the basic example, we use slice() function to extract string from this string−

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

Output

Following is the output −

slice: is tut

Example 2: Extract Characters

In this example, we use the slice() function to extract characters only from the specified index by iterable −

fun main() {
   val input = "Kotlin tutorialspoint"

   // Extract characters at indices 0, 4, 8
   val sliceIndices = input.slice(listOf(0, 4, 8))
   println("characters at index 0, 4, 8 respectively:" + sliceIndices)
}

Output

Following is the output −

characters at index 0, 4, 8 respectively:Kiu

Example 3: Extract Vowels Characters

In this example, we use the slice() function with a dynamic condition −

fun main() {
   val input = "tutorialspoint India"

   // Extract characters at indices where the character is a vowel
   val vowels = input.slice(input.indices.filter { input[it] in "AEIOUaeiou" })
   println("Vowels of this string: " + vowels)
}

Output

Following is the output −

Vowels of this string: uoiaoiIia
kotlin_strings.htm
Advertisements