Go Program to Check if a String Is a Palindrome

1. Introduction

A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward, disregarding spaces, punctuation, and capitalization. Examples include the word "radar" and the number "121". Palindromes are frequently used in wordplay and riddles.

In this blog post, we will learn how to create a Go program that determines whether a provided string is a palindrome.

2. Program Overview

Our Go program will:

1. Take a string from the user.

2. Analyze the string to ascertain whether it reads the same backward as forward.

3. Convey to the user if the string is a palindrome.

3. Code Program

// declaration of the main package.
package main

// The fmt and strings packages are enlisted to aid in input-output operations and string manipulations, respectively.
import (
    "fmt"
    "strings"
)

// Function to verify if a string is a palindrome.
func isPalindrome(s string) bool {
    s = strings.ToLower(s) // Normalize the string to lowercase
    runes := []rune(s)
    for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
        if runes[i] != runes[j] {
            return false
        }
    }
    return true
}

// The crux of our program, the main function.
func main() {
    var inputString string

    // A cue for the user to enter their string.
    fmt.Print("Enter a string to check if it's a palindrome: ")
    fmt.Scanln(&inputString)

    // The moment of truth, relaying if the string is a palindrome.
    if isPalindrome(inputString) {
        fmt.Printf("\"%s\" is a palindrome.\n", inputString)
    } else {
        fmt.Printf("\"%s\" is not a palindrome.\n", inputString)
    }
}

Output:

As an exemplar, if a user inputs the string radar, the program's revelation will be:
"radar" is a palindrome.

4. Step By Step Explanation

1. Package and Import: We inaugurate our guide with the package main declaration, earmarking the onset of the program. The fmt and strings packages are incorporated for handling I/O and string transformations.

2. Palindrome Verification Function: The isPalindrome function is the linchpin of our palindrome validation. Initially, the string is standardized to lowercase to ensure uniformity. The function then employs a two-pointer methodology, comparing characters from the extremities of the string and moving inwards.

3. User Engagement & Verdict: The variable inputString holds the user's input. Upon procuring the string, our program invokes the isPalindrome function and unfurls the verdict to the user.

Comments