w3resource

Kotlin function: Check if a string is a palindrome


Write a Kotlin function that checks if a string is a palindrome or not.


Pre-Knowledge (Before you start!)

  • Basic Kotlin Syntax.
  • Kotlin Functions.
  • String Manipulation.
  • Regular Expressions.
  • Conditional Logic.
  • Printing Output.

Hints (Try before looking at the solution!)

  • Define the Function.
  • Clean the String.
  • Reverse the String.
  • Compare Strings.
  • Test the Function.
  • Common Errors to Avoid:
    • Forgetting to clean the string.
    • Misusing reversed() or comparison logic.
    • Not handling edge cases correctly.

Sample Solution:

Kotlin Code:

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

fun main() {
    val str1 = "Madam"
    val str2 = "Kotlin"

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

Sample Output:

Madam is palindrome: true
Kotlin is palindrome: false

Explanation:

In the above exercise -

  • The "isPalindrome()" function takes a str parameter, which represents the string to be checked.
  • Within the function, the input string str is first cleaned by converting it to lowercase and removing any non-alphanumeric characters using a regular expression.
  • The cleaned string cleanStr is compared with its reversed form (cleanStr.reversed()) using the == operator.
  • If the cleaned string and its reversed form are equal, the input string is a palindrome, and the function returns true. Otherwise, it returns false.
  • In the "main()" function, two sample strings (str1 and str2) are defined.
  • The "isPalindrome()" function is called for each string, and the result is printed to the console.

Go to:


PREV : Kotlin function: Reverse a string.
NEXT : Print message without return.

Kotlin Editor:


Improve this sample solution and post your code through Disqus

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.