Joseph Jude

Swift Challenge 002: Check if a string is palindrome

2015.12.19 / code / swift /

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:

To Improve:

Uses:

Git Repository / All Swift Challenges

Got comments? Tweet it, or comment below.


Share this post on

Twitter | | |