Prudent Devs

Swift Challenge 002: Check if a string is palindrome

Check if a string is a palindrome -- it reads the same forwards as backwards like racecar

Challenge: Write a program to check if the string entered by the user is a palindrome. That is that it reads the same forwards as backwards like “racecar”

Logic: Reverse the string and compare. If equal, then it is palindrome

Code:

print("Enter a string: ")
let userInput = readLine(stripNewline: true)!

let reverse = String(userInput.characters.reverse())

if (reverse == userInput) {
  print("\(userInput) is a palindrome")
} else {
  print("\(userInput) is not a palindrome")
}

Explanation:

  • readLine reads input from console. It returns an optional string. Unwrap it with !
  • .characters gives characters in a string as an array
  • reverse() reverses the array (remember array is an ordered collection)

To Improve:

  • exit if no input given
  • be on continuous loop until ^D is pressed (more like a console app)

Uses:

  • reading from console
  • strings as array of characters
  • string comparison

Git Repository / All Swift Challenges

Got comments? Tweet it, or comment below.

Published On:
Under: #code , #swift
Sign up for my newsletter