Kotlin String.any()

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

ParameterDescription
predicateA lambda function that takes a character as an argument and returns true or false.
Parameter of String any() function

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.

  1. Take a string value in mixedCaseString.
  2. Define a predicate function that checks if a character is uppercase.
  3. Call any() function on mixedCaseString with the defined predicate. The function returns true if any character is uppercase, and false otherwise.
  4. 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.

  1. Take a string value in numericString.
  2. Define a predicate function that checks if a character is a digit.
  3. Call any() function on numericString with the defined predicate. The function returns true if any character is a digit, and false otherwise.
  4. 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.