w3resource

Scala Program: Check Palindrome using if/else and pattern matching

Scala Control Flow Exercise-8 with Solution

Write a Scala program to check if a given string is a palindrome using if/else statements and pattern matching.

Sample Solution:

Scala Code:

object PalindromeChecker {
  def main(args: Array[String]): Unit = {
        val str: String = "madam" // String you want to check
    //  val str: String = "Scala" // String you want to check

    // Check using if/else statements
    val isPalindrome: Boolean = checkPalindromeIfElse(str)
    if (isPalindrome) {
      println(s"The string $str is a palindrome.")
    } else {
      println(s"The string $str is not a palindrome.")
    }

  }

  def checkPalindromeIfElse(str: String): Boolean = {
    val reversed = str.reverse
    if (str == reversed) {
      true
    } else {
      false
    }
  }

  def checkPalindromeMatch(str: String): Boolean = {
    str.reverse match {
      case `str` => true
      case _     => false
    }
  }
}

Sample Output:

The string madam is a palindrome.
The string Scala is not a palindrome.

Explanation:

In the above exercise -

  • First we define a variable str and assign it a value ("level" in this case) representing the string we want to check for palindromes.
  • We have two functions: "checkPalindromeIfElse()" and "checkPalindromeMatch()". The first function uses if/else statements to check if the given string is a palindrome. It reverses the string using the reverse method and compares it with the original string. If they are equal, it returns true; otherwise, it returns false.
  • The second function, "checkPalindromeMatch()", uses pattern matching. It reverses the string and matches it against the original string using a pattern. If the reversed string matches the original string, it returns true; otherwise, it returns false.
  • We call both functions and print the results using println. If the returned value is true, the string is a palindrome; otherwise, it is not a palindrome.

Scala Code Editor :

Previous: Scala program to find the sum of array elements using a for loop.
Next: Count vowels with if/else and pattern matching.

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://www.w3resource.com/scala-exercises/control-flow/scala-control-flow-exercise-8.php