Kotlin program to remove first and last characters of a string

Introduction :

Kotlin provides different methods to manipulate a string. In this post, we will learn different Kotlin string methods to remove the first and last characters of a string.

drop(n: Int) :

drop takes one integer as its argument and removes the first characters from the string that we are passing as the argument. It returns one new string.

  • n = 0 : It returns the same string
  • n > 0 & n < string-length : removes the first n characters from the string and returns a new string.
  • n < 0 : Throws IllegalArgumentException
  • n >= string-length : Returns one empty string

If its value is negative, it throws IllegalArgumentException.

Example of drop :

fun main() {
    val givenStr = "Hello World !!"

    println("drop(0) : ${givenStr.drop(0)}")
    println("drop(6) : ${givenStr.drop(6)}")
    println("drop(110) : ${givenStr.drop(110)}")
}

It will print :

drop(0) : Hello World !!
drop(6) : World !!
drop(110) :

The last result is an empty string.

dropLast(n: Int) :

Similar to drop, dropLast is used to remove the last characters of a string. It takes one integer value as the parameter and removes the last characters of the string equal to that parameter. If it is negative, it throws IllegalArgumentException.

For example :

fun main() {
    val givenStr = "Hello World !!"

    println(givenStr.dropLast(2))
}

It prints :

Hello World

removeRange(range: IntRange) :

This method removes all characters defined by the range. We can remove the start characters, end characters or middle characters using this method. For invalid index, it throws one IndexOutOfBoundsException. Note that the last index of the range is also removed.

For example, we can remove the first and the last characters of a string as like below :

fun main() {
    val givenStr = "Hello World !!"

    println(givenStr.removeRange(0.rangeTo(5)))
    println(givenStr.removeRange(5 until givenStr.length))
}

It will print :

World !!
Hello

removeRange(startIndex: Int, endIndex: Int) :

Another variant of removeRange. It removes all characters defined by the start and end index. If the indices are invalid, it throws NegativeArraySizeException. Note that the character at endIndex is not removed. All characters before it are removed.

fun main() {
    val givenStr = "Hello World !!"

    println(givenStr.removeRange(0,5))
}

Output :

World !!

Convert to a StringBuilder and use removeRange :

removeRange methods are also available in StringBuilder class. The definitions are the same as we have seen for strings. We can convert a string to a StringBuilder and use these methods to remove start or ending characters.

fun main() {
    val givenStr = "Hello World !!"

    println(StringBuilder(givenStr).removeRange(0,6).toString())
}

It will print:

World !!

Similar tutorials :