Kotlin String drop()

Kotlin String drop() Tutorial

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

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

Syntax

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

fun String.drop(
    n: Int
): String

where

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

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

Examples for String drop() function

1. Remove First 3 Characters from the String

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

  1. Take a string value in originalString.
  2. Call drop() function on originalString with the value 3 as the argument. The function returns a new string with the first three characters dropped.
  3. You may print the resulting string to the console output.

Kotlin Program

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

    // Using drop() to exclude the first three characters
    val resultString = originalString.drop(3)

    // Printing the original string and the result
    println("Original String:\n$originalString\n")
    println("Result String:\n$resultString")
}

Output

Original String:
Hello World!

Result String:
lo World!

2. Dropping All Characters

In this example, we’ll use drop() to create an empty string by dropping all characters from a given string.

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

Kotlin Program

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

    // Using drop() to create an empty string
    val resultString = originalString.drop(originalString.length)

    // Printing the original string and the result
    println("Original String:\n$originalString\n")
    println("Result String:\n$resultString")
}

Output

Original String:
Hello World!

Result String:

Summary

In this tutorial, we’ve covered the drop() function in Kotlin strings, its syntax, and how to use it to create substrings by excluding a specified number of characters from the beginning of the original string. This function is useful for manipulating string data based on the desired exclusion criteria.