Swift Program to Check Palindrome

1. Introduction

A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization). Examples of palindromic words include "radar" and "level". In this guide, we'll create a Swift program to check if a given string is a palindrome.

2. Program Overview

Our strategy is straightforward. We'll remove any non-alphanumeric characters and spaces from the input string, convert the string to lowercase, and then check if this cleaned string is the same when read backward. If it is, then our input is a palindrome.

3. Code Program

// Sample string to check
let originalString = "A man, a plan, a canal, Panama!"

// Clean the string: Remove non-alphanumeric characters, convert to lowercase
let cleanedString = originalString.lowercased().filter { $0.isLetter }

// Check if string is palindrome
let isPalindrome = cleanedString == String(cleanedString.reversed())

// Print result
if isPalindrome {
    print("\"\(originalString)\" is a palindrome.")
} else {
    print("\"\(originalString)\" is not a palindrome.")
}

Output:

"A man, a plan, a canal, Panama!" is a palindrome.

4. Step By Step Explanation

1. let originalString = "A man, a plan, a canal, Panama!": We initialize a string originalString with a classic example of a palindromic sentence.

2. let cleanedString = originalString.lowercased().filter { $0.isLetter }: The given string is cleaned in two steps:

- Using lowercased() to ensure our check isn't case-sensitive.- The filter method combined with $0.isLetter to retain only the alphanumeric characters, effectively removing spaces, punctuation, etc.

3. let isPalindrome = cleanedString == String(cleanedString.reversed()): Here, we check if the cleaned string is equivalent to its reversed version. If it is, our isPalindrome flag is set to true.

4. The subsequent if-else structure prints out whether the original string is a palindrome or not.


Comments