Kotlin String dropLast()

Kotlin String dropLast() Tutorial

The String.dropLast() function in Kotlin is used to create a substring by excluding characters from the end of the original string. It returns a new string that consists of the remaining characters after dropping the specified number of characters from the end.

In this tutorial, we’ll explore the syntax of the dropLast() function and provide examples of its usage in Kotlin strings.

Syntax

The syntax of the dropLast() function is as follows:

fun String.dropLast(
    n: Int
): String

where

ParameterDescription
nThe number of characters to drop from the end of the string.
Parameter of String.dropLast() function

The n parameter represents the number of characters to exclude from the end of the string. The function returns a new string containing the remaining characters.

Examples for String dropLast() function

1. Dropping Last Three Characters from String

In this example, we’ll use dropLast() to create a substring by excluding the last three characters from a given string.

  1. Take a string value in word.
  2. Call dropLast() function on word with the argument 3 to drop the last three characters. The function returns a new string with the specified number of characters dropped.
  3. You may print the resulting string to the console output.

Kotlin Program

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

    // Using dropLast() to exclude the last three characters
    val resultString = word.dropLast(3)

    // Printing the original word and the result
    println("Original Word: $word")
    println("Result String: $resultString")
}

Output

Original Word: Hello World!
Result String: Hello Wor

2. Dropping All Characters

In this example, we’ll use dropLast() to create an empty string by excluding all characters from the end of a given string.

  1. Take a string value in text.
  2. Call dropLast() function on text with the argument greater than or equal to the length of the string. The function returns an empty string.
  3. You may print the resulting string to the console output.

Kotlin Program

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

    // Using dropLast() to exclude all characters
    val emptyString = text.dropLast(text.length)

    // Printing the original text and the result
    println("Original Text: $text")
    println("Empty String: $emptyString")
}

Output

Original Text: Hello
Empty String: 

Summary

In this tutorial, we’ve covered the dropLast() function in Kotlin strings, its syntax, and how to use it to create substrings by excluding characters from the end of the original string. This function is useful for scenarios where you need to remove a specific number of characters from the end of a string.