Kotlin string slice method example

Introduction :

Kotlin String class provides one method called slice to get one sub-string containing the characters defined by the method argument. It has two variants. In this post, I will show you how to use this method with examples :

public fun String.slice(indices: IntRange): String :

It takes one IntRange argument and returns one string containing the characters at the specified positions defined by the indices.

For example :

fun main() {
    val str = "The quick brown fox jumps over the lazy dog"

    println(str.slice(1..14))
    println(str.slice(20 downTo 1))
}

It will print :

he quick brown
j xof nworb kciuq eh

If the range is in reverse order, the final string is also reversed.

public inline fun String.slice(indices: Iterable): String :

This is another variant of slice that takes one Iterable. For example :

fun main() {
    val str = "The quick brown fox jumps over the lazy dog"

    println(str.slice(listOf(0,2,4,6,8,10)))
}

It will print :

Teqikb

The slice in this example creates one subarray by taking the characters at even indices from 0 to 10. We can create one list of indices and slice will return us one string by picking the characters at these indices.

Combining all examples :

fun main() {
    val str = "The quick brown fox jumps over the lazy dog"

    println(str.slice(1..14))
    println(str.slice(20 downTo 1))
    println(str.slice(listOf(0,2,4,6,8,10)))
}

Output :

he quick brown
j xof nworb kciuq eh
Teqikb

Kotlin string slice

Similar tutorials :

Where is the color and why codevscolor ?

Long story short, I love paintings and I paint on weekends. We(me and my wife) have one Youtube channel. Below is a video that I did recently. If you love this please do subscribe to support us 😊❤️❤️