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
Parameter | Description |
---|---|
n | The number of characters to drop from the beginning of the string. |
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.
- Take a string value in
originalString
. - Call
drop()
function onoriginalString
with the value3
as the argument. The function returns a new string with the first three characters dropped. - 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.
- Take a string value in
text
. - Call
drop()
function ontext
with the length of the string as the argument. The function returns an empty string. - 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.