Check Whether a String is Palindrome or Not in Go



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.


What is a Palindrome

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'.


Syntax

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
}


Example 1: Checking if a string is a palindrome

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,

  1. Define a function named isPalindrome that takes one parameter s of type string.
  2. Get the length of the string n.
  3. Use a for loop to iterate from 0 to n/2.
  4. In each iteration, compare the character at index i with the character at index n-i-1. If they are not equal, return false.
  5. If the loop completes without finding unequal characters, return true.
  6. In the main function, call the isPalindrome function with sample strings and print the results.

Go Program

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)
        }
    }
}

Output

'madam' is a palindrome
'racecar' is a palindrome
'hello' is not a palindrome
'12321' is a palindrome