How to check whether a string is a palindrome, ignoring spaces and case in Scala

1 Answer

0 votes
import scala.util.matching.Regex

object PalindromeChecker {
  def isPalindrome(str: String): Boolean = {
    // Normalize the string: remove spaces and convert to lowercase
    val pattern: Regex = "\\s+".r
    val normalizedStr = pattern.replaceAllIn(str, "").toLowerCase

    // Reverse the normalized string and compare
    val reversedStr = normalizedStr.reverse

    normalizedStr == reversedStr
  }

  def main(args: Array[String]): Unit = {
    println(s"Is palindrome: ${isPalindrome("A man a plan a canal Panama")}")
    println(s"Is palindrome: ${isPalindrome("abcDefg")}")
  }
}


 
/*
run:
 
Is palindrome: true
Is palindrome: false
 
*/

 



answered May 16, 2025 by avibootz
...