Project 9: Palindrome checker
Complete video course: Udemy
Introduction
A palindrome checker is a program that checks whether or not a word is a palindrome. A palindrome is a word that reads the same both forwards and backwards. For example, racecar in reverse is still racecar, making it a palindrome. Nemuel in reverse is leumen, making it NOT a palindrome!
We will prompt the user for a word and read their input, check whether or not the reverse of the word is similar to the original word itself, and display the results back to the user.
Practical
Boilerplate code:
package main
import (
)
func main() {
}
First, we prompt the user for a word and read their input:
import (
"fmt"
)
var word string
fmt.Print("Enter the word to check: ")
fmt.Scanln(&word)
Next, in the spirit of separating concerns, we will create a function called reverseWord that takes in a word, reverses it, and returns that reversed version:
func reverseWord(word string) string {
reversed := ""
for i := len(word) - 1; i >= 0; i-- {
reversed += string(word[i])
}
return reversed
}
In the above snippet, we first declare an empty string variable called reversed which will contain the result of the word reversal. Next, we use a for loop, starting from the last letter of the word and moving towards the first, appending each of these characters to the reversed string in order. Since indexing starts from 0, the final index is obtained by the length of the string - 1 (len(word) - 1). We append each character to the reversed string variable using the add and assign operator (+=). Finally, we return the reversed version from the function.
Back in the main function, we will call the above function to obtain the reverse of the user-provided word:
reversed := reverseWord(word)
Finally, we can have a simple conditional statement checking whether the reversed word is similar to the original word, in which case we display that the word is indeed a palindrome. Otherwise, we display that it is not a palindrome:
if reversed == word {
fmt.Printf("%s is a palindrome\n", word)
} else {
fmt.Printf("%s is not a palindrome\n", word)
}
Complete code:
package main
import (
"fmt"
)
func reverseWord(word string) string {
reversed := ""
for i := len(word) - 1; i >= 0; i-- {
reversed += string(word[i])
}
return reversed
}
func main() {
var word string
fmt.Print("Enter the word to check: ")
fmt.Scanln(&word)
reversed := reverseWord(word)
if reversed == word {
fmt.Printf("%s is a palindrome\n", word)
} else {
fmt.Printf("%s is not a palindrome\n", word)
}
}