In this tutorial, we will learn how to check whether a string is a palindrome in Go. We will cover the basic concept of palindromes and implement a function to perform the check.
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 palindromes include 'madam', 'racecar', and '12321'.
The syntax to check if a string is a palindrome in Go is:
func isPalindrome(s string) bool {
n := len(s)
for i := 0; i < n/2; i++ {
if s[i] != s[n-i-1] {
return false
}
}
return true
}
We can create a function to check if a given string is a palindrome by comparing characters from both ends of the string.
For example,
isPalindrome
that takes one parameter s
of type string
.n
.for
loop to iterate from 0 to n/2
.i
with the character at index n-i-1
. If they are not equal, return false
.true
.isPalindrome
function with sample strings and print the results.package main
import (
"fmt"
)
func isPalindrome(s string) bool {
n := len(s)
for i := 0; i < n/2; i++ {
if s[i] != s[n-i-1] {
return false
}
}
return true
}
func main() {
// Sample strings
strings := []string{"madam", "racecar", "hello", "12321"}
// Check and print if each string is a palindrome
for _, str := range strings {
result := isPalindrome(str)
if result {
fmt.Printf("'%s' is a palindrome\n", str)
} else {
fmt.Printf("'%s' is not a palindrome\n", str)
}
}
}
'madam' is a palindrome 'racecar' is a palindrome 'hello' is not a palindrome '12321' is a palindrome