Scala program to check if a string is a palindrome

1. Introduction

A palindrome is a word, phrase, number, or other sequences of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization). Examples include words like "radar" or "level". In this blog post, we will walk through a Scala program that checks if a given string is a palindrome.

2. Program Steps

1. Set up the Scala environment.

2. Create an object to house the main function.

3. Define the string that needs to be checked.

4. Implement a function to determine if the string is a palindrome.

5. Call the palindrome-checking function and display the result.

6. Run the program.

3. Code Program

object PalindromeCheckerApp {
  def main(args: Array[String]): Unit = {
    // Define the string
    val str = "radar"

    println(s"Checking if the string '$str' is a palindrome.")

    // Check and print the result using the isPalindrome function
    if (isPalindrome(str))
      println(s"\nThe string '$str' is a palindrome.")
    else
      println(s"\nThe string '$str' is not a palindrome.")
  }

  // Function to determine if the string is a palindrome
  def isPalindrome(s: String): Boolean = {
    val cleanedString = s.toLowerCase.replaceAll("[^a-z]", "")
    cleanedString == cleanedString.reverse
  }
}

Output:

Checking if the string 'radar' is a palindrome.
The string 'radar' is a palindrome.

Explanation:

1. We start with an object named PalindromeCheckerApp. In Scala, the main method, which acts as the entry point of the program, resides within an object.

2. Inside the main function, we define a value str representing the string that we want to check.

3. A message is printed to inform the user about the string being checked.

4. We employ the isPalindrome function to check if the string is a palindrome. This function first cleans the string by converting it to lowercase and removing any non-alphabet characters. It then checks if the cleaned string is the same when reversed.

5. Based on the result of the isPalindrome function, we print out whether the string is a palindrome or not.

6. The output first notes the string that's being checked and then provides the result of the palindrome check.


Comments