In this tutorial, you shall learn how to remove first N characters from a given string in Kotlin, using String.drop() function, with examples.

Kotlin – Remove First N Characters from String

To remove first N characters from a String in Kotlin, use String.drop() method.

Given a string str1, and if we would like to remove first n characters from this string str1, call drop() method on string str1 and pass the integer n as argument to the method as shown below.

</>
Copy
str1.drop(n)

drop() method returns a new string with the first n characters removed from the given string.

Examples

1. Remove first three characters in string

In this example, we will take a string in str1, and drop the first 3 characters of the string str1.

Kotlin Program

</>
Copy
fun main(args: Array<String>) {
    val str1 = "abcdefg"
    val n = 3
    val result = str1.drop(n)
    println("Original String  : " + str1)
    println("Resulting String : " + result)
}

Output

Original String  : abcdefg
Resulting String : defg

2. Number of characters to be removed > Given string length

If the value of n is greater than the original string length, then drop() method returns an empty string.

Kotlin Program

</>
Copy
fun main(args: Array<String>) {
    val str1 = "abcdefg"
    val n = 10
    val result = str1.drop(n)
    println("Original String  : " + str1)
    println("Resulting String : " + result)
}

Output

Original String  : abcdefg
Resulting String : 

Conclusion

In this Kotlin Tutorial, we learned how to remove first N characters from a given string using String.drop() method, with the help of Kotlin example programs.