Palindrome Checker in Go
This program checks if a given string is a palindrome. A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward (ignoring spaces, punctuation, and capitalization).
Go Program
package main
import (
"fmt"
"strings"
"unicode"
)
// isPalindrome function checks if the given string is a palindrome
func isPalindrome(s string) bool {
// Convert the string to lower case and remove non-alphanumeric characters
cleaned := ""
for _, r := range s {
if unicode.IsLetter(r) || unicode.IsDigit(r) {
cleaned += strings.ToLower(string(r))
}
}
// Check if the cleaned string is a palindrome
length := len(cleaned)
for i := 0; i < length/2; i++ {
if cleaned[i] != cleaned[length-1-i] {
return false
}
}
return true
}
func main() {
// Example strings to check
examples := []string{
"A man, a plan, a canal, Panama",
"racecar",
"Hello, World!",
"Was it a car or a cat I saw?",
}
// Check each string and print the result
for _, example := range examples {
result := isPalindrome(example)
fmt.Printf("Is \"%s\" a palindrome? %v\n", example, result)
}
}
Explanation
The isPalindrome
function performs the following steps:
- Normalize the string: The function converts the string to lower case and removes all non-alphanumeric characters. This is done using a for loop that iterates over each character in the string and appends only letters and digits to the cleaned string.
- Check for palindrome: The function checks if the cleaned string reads the same backward as forward. It does this by comparing characters from the start and end of the string moving towards the center. If any characters do not match, the function returns
false
. If all characters match, the function returnstrue
.
Running the Program
To run the program, save the code in a file named main.go
and use the following commands:
$ go mod init palindrome_checker
$ go run main.go
The program will output:
Is "A man, a plan, a canal, Panama" a palindrome? true
Is "racecar" a palindrome? true
Is "Hello, World!" a palindrome? false
Is "Was it a car or a cat I saw?" a palindrome? true