Kotlin String all() Tutorial
The all()
function in Kotlin is used to check whether all characters in the string satisfy the given predicate. It returns true
if all characters match the predicate, and false
otherwise.
In this tutorial, we’ll explore the syntax of the all()
function and provide examples of its usage in Kotlin strings.
Syntax
The syntax of the all()
function is as follows:
fun CharSequence.all(
predicate: (Char) -> Boolean
): Boolean
where
Parameter | Description |
---|---|
predicate | A lambda function that takes a character as an argument and returns true or false . |
The all()
function applies the given predicate
to each character of the string. If all characters satisfy the predicate, the function returns true
; otherwise, it returns false
.
Examples for String all() function
1. Checking if All Characters are Digits
In this example, we’ll use all()
to check if all characters in a string are digits.
- Take a string value in
numericString
. - Define a
predicate
function that checks if a character is a digit. - Call
all()
function onnumericString
with the definedpredicate
. The function returnstrue
if all characters are digits, andfalse
otherwise. - You may print the result to the console output.
Kotlin Program
fun main() {
val numericString = "12345"
// Using all() to check if all characters are digits
val allDigits = numericString.all { it.isDigit() }
// Printing the original string and the result
println("Numeric String: $numericString")
println("All Digits: $allDigits")
}
Output
Numeric String: 12345
All Digits: true
2. Checking if All Characters are either ‘a’, ‘b’, or ‘c’
In this example, we’ll use all()
to check if all characters in a string are ‘a’, ‘b’, and/or ‘c’.
- Take a string value in
myString
. - Define a
predicate
function that checks if a character is ‘a’, ‘b’, or ‘c’. - Call
all()
function onmyString
with the definedpredicate
. The function returnstrue
if all characters are ‘a’, ‘b’, or ‘c’,false
otherwise. - Use the returned value as a condition in if else statement, and print the output to console.
Kotlin Program
fun main() {
val myString = "abbcabaabacb"
// Using all()
if (myString.all { it == 'a' || it == 'b' || it == 'c' }) {
println("The string contains only a,b, and c.")
} else {
println("There are characters other than a,b, and c.")
}
}
Output
The string contains only a,b, and c.
Summary
In this tutorial, we’ve covered the all()
function in Kotlin strings, its syntax, and how to use it to check if all characters in a string satisfy a given predicate. This function provides a convenient way to perform a condition check on all characters within a string.