w3resource

Anonymous Kotlin function: Check palindrome string

Kotlin Lambda: Exercise-8 with Solution

Write an anonymous Kotlin function to check if a string is a palindrome.

Sample Solution:

Kotlin Code:

fun main() {
    val isPalindrome: (String) -> Boolean = { str ->
        val cleanStr = str.lowercase().replace(Regex("[^a-zA-Z0-9]"), "")
        cleanStr == cleanStr.reversed()
    }

    val str1 = "Madam"
    val str2 = "Kotlin"

    println("$str1 is a palindrome: ${isPalindrome(str1)}")
    println("$str2 is a palindrome: ${isPalindrome(str2)}")
}

Sample Output:

Madam is a palindrome: true
Kotlin is a palindrome: false

Explanation:

In the above exercise -

Inside "main()" function we define an anonymous function isPalindrome with the type (String) -> Boolean. This function takes a single string argument and returns a Boolean indicating whether the string is a palindrome or not.

The isPalindrome function implements the following steps:

  • It converts the input string to lowercase using toLowerCase() to ignore case sensitivity.
  • It removes any non-alphanumeric characters from the string using replace(Regex("[^a-zA-Z0-9]"), "").
  • It checks if the cleaned string is equal to its reversed version using the == operator.
  • The result of the equality comparison is returned as a Boolean value.

Kotlin Editor:


Previous: Convert list of strings to uppercase with lambda.
Next: Calculate a factorial.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.