Kotlin String.any() Tutorial
The String.any()
function in Kotlin is used to check whether any character in the string satisfies the given predicate. It returns true
if at least one character matches the predicate, and false
otherwise.
In this tutorial, we’ll explore the syntax of the any()
function and provide examples of its usage in Kotlin strings.
Syntax
The syntax of the any()
function is as follows:
fun CharSequence.any(
predicate: (Char) -> Boolean
): Boolean
where
Parameter | Description |
---|---|
predicate | A lambda function that takes a character as an argument and returns true or false . |
The any()
function applies the given predicate
to each character of the string. If at least one character satisfies the predicate, the function returns true
; otherwise, it returns false
.
Examples for String any() function
1. Checking if Any Character is Uppercase
In this example, we’ll use any()
to check if any character in a string is uppercase.
- Take a string value in
mixedCaseString
. - Define a
predicate
function that checks if a character is uppercase. - Call
any()
function onmixedCaseString
with the definedpredicate
. The function returnstrue
if any character is uppercase, andfalse
otherwise. - You may print the result to the console output.
Kotlin Program
fun main() {
val mixedCaseString = "HelloKotlin"
// Using any() to check if any character is uppercase
val anyUppercase = mixedCaseString.any { it.isUpperCase() }
// Printing the original string and the result
println("Mixed Case String: $mixedCaseString")
println("Any Uppercase: $anyUppercase")
}
Output
Mixed Case String: HelloKotlin
Any Uppercase: true
2. Checking if Any Character is a Digit
In this example, we’ll use any()
to check if any character in a string is a digit.
- Take a string value in
numericString
. - Define a
predicate
function that checks if a character is a digit. - Call
any()
function onnumericString
with the definedpredicate
. The function returnstrue
if any character is a digit, andfalse
otherwise. - You may print the result to the console output.
Kotlin Program
fun main() {
val numericString = "Hello123"
// Using any() to check if any character is a digit
val anyDigit = numericString.any { it.isDigit() }
// Printing the original string and the result
println("Numeric String: $numericString")
println("Any Digit: $anyDigit")
}
Output
Numeric String: Hello123
Any Digit: true
Summary
In this tutorial, we’ve covered the any()
function in Kotlin strings, its syntax, and how to use it to check if at least one character in a string satisfies a given predicate. This function provides a convenient way to perform a condition check on any character within a string.