How to remove the first n characters from a string in Kotlin

How to remove the first N characters from a string in Kotlin:

In this post, we will learn different ways to remove the first N characters from a string in Kotlin. Kotlin string class provides a couple of inbuilt methods and we can use these to do different operations on a Kotlin string.

Method 1: By using the drop() method:

The drop method can be used to remove the first n characters from a string in Kotlin. It takes the number of characters to remove as its parameter and returns the modified string.

fun String.drop(n: Int): String

Let’s try it with an example:

fun main() {
    val givenStringArray = arrayOf("hello", "hello world", "  hello", "12 3hello world!!")

    for (str in givenStringArray) {
        println(str + " : " + str.drop(3))
    }
}

In this example, givenStringArray is an array of strings. The for loop iterates over the strings of the array one by one and it is removing the first three characters from the string.

If you run this program, it will print the below output:

hello : lo
hello world : lo world
  hello : ello
12 3hello world!! : 3hello world!!

As you can see here, the first three characters are removed from each string.

Method 2: By using removeRange:

The removeRange is another inbuilt method to remove a part of a string at a given range. This method is defined as:

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

Here startIndex and endIndex are starting and end indices. startIndex is the index of the first character to remove from the string. It will remove all characters up to endIndex - 1.

To remove the first n characters of a string, we can provide 0 as the startIndex and n + 1 as the endIndex.

We can also pass an IntRange object as its parameter.

Example with removeRange and startIndex, endIndex:

fun String.removeRange(range: IntRange): String

Let’s try it with an example:

fun main() {
    val givenStringArray = arrayOf("hello", "hello world", "  hello", "12 3hello world!!")

    for (str in givenStringArray) {
        println(str + " : " + str.removeRange(0, 3))
    }
}

It will remove the first three characters of the strings.

hello : lo
hello world : lo world
  hello : ello
12 3hello world!! : 3hello world!!

Example with removeRange and IntRange:

Let’s try it with IntRange:

fun main() {
    val givenStringArray = arrayOf("hello", "hello world", "  hello", "12 3hello world!!")

    for (str in givenStringArray) {
        println(str + " : " + str.removeRange(IntRange(0, 2)))
    }
}

Note that the second parameter of IntRange is inclusive i.e. it will remove all characters from index 0 to index 2.

Kotlin example remove first n characters from string

You might also like: