Kotlin String dropWhile() Tutorial
The String.dropWhile()
function in Kotlin is used to create a substring by excluding characters from the beginning of the original string based on a given predicate condition. It returns a new string that consists of the remaining characters after dropping the prefix that matches the specified condition.
In this tutorial, we’ll explore the syntax of the dropWhile()
function and provide examples of its usage in Kotlin strings.
Syntax
The syntax of the dropWhile()
function is as follows:
fun String.dropWhile(
predicate: (Char) -> Boolean
): String
where
Parameter | Description |
---|---|
predicate | A function that takes a character and returns true if the character should be dropped, or false otherwise. |
The predicate
parameter is a function that defines the condition for dropping characters from the beginning of the string. The function returns a new string containing the remaining characters.
Examples for String dropWhile() function
1. Dropping Prefix While Character is a Vowel
In this example, we’ll use dropWhile()
to create a substring by excluding characters from the beginning of a string while the character is a vowel.
- Take a string value in
text
. - Define a predicate function that returns
true
for vowels andfalse
for other characters. - Call
dropWhile()
function ontext
with the defined predicate. The function returns a new string with the prefix dropped based on the predicate condition. - You may print the resulting string to the console output.
Kotlin Program
fun main() {
val text = "awesome"
// Defining a predicate function
val isVowel: (Char) -> Boolean = { it.lowercase() in "aeiou" }
// Using dropWhile() to exclude characters while they are vowels
val resultString = text.dropWhile(isVowel)
// Printing the original string and the result
println("Original Text:\n$text\n")
println("Result String:\n$resultString")
}
Output
Original Text:
awesome
Result String:
wesome
Summary
In this tutorial, we’ve covered the dropWhile()
function in Kotlin strings, its syntax, and how to use it to create substrings by excluding characters from the beginning of the original string based on a specified condition. This function is handy for manipulating string data by dynamically determining the exclusion criteria.