w3resource

Scala function: Check if a string is a palindrome

Scala Function Exercise-5 with Solution

Write a Scala function to check if a given string is a palindrome.

Sample Solution:

Scala Code:

object PalindromeChecker {
  def isPalindrome(str: String): Boolean = {
    val reversed = str.reverse
    str == reversed
  }

  def main(args: Array[String]): Unit = {
    val input1 = "madam"
    val isPalindrome1 = isPalindrome(input1)
    println(s"$input1 is a palindrome: $isPalindrome1")

    val input2 = "scala"
    val isPalindrome2 = isPalindrome(input2)
    println(s"$input2 is a palindrome: $isPalindrome2")
  }
}

Sample Output:

madam is a palindrome: true
scala is a palindrome: false

Scala Code Editor :

Previous: Reverse a Given String.
Next: Find the maximum element.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/scala-exercises/function/scala-function-exercise-5.php