Introduction
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 “level”. This program is designed to check if a given string is a palindrome in Go programming language.
Objective
The main objective of this program is to check if a given string is a palindrome. It will read the string input, process it by ignoring spaces and case, and then determine whether it can be reversed to match the original string.
Go Code for Palindrome Check
package main import ( "fmt" "strings" ) // Function to check if the string is a palindrome func isPalindrome(s string) bool { // Remove spaces and convert to lowercase s = strings.ToLower(strings.ReplaceAll(s, " ", "")) // Loop through the string and check characters from both ends for i := 0; i < len(s)/2; i++ { if s[i] != s[len(s)-i-1] { return false } } return true } func main() { // Take input from the user var input string fmt.Print("Enter a string to check if it is a palindrome: ") fmt.Scanln(&input) // Check if the input string is a palindrome if isPalindrome(input) { fmt.Println("The string is a palindrome.") } else { fmt.Println("The string is NOT a palindrome.") } }
Explanation of the Program
The program works by performing the following steps:
- Input Handling: The program first prompts the user to input a string that they wish to check for being a palindrome.
- Preprocessing: The
isPalindrome
function processes the input string by removing any spaces and converting all characters to lowercase. This is to ensure the comparison is case-insensitive and ignores any spaces. - Palindrome Check: The program then compares characters from the start and end of the string. If any pair of characters don’t match, the function returns
false
, indicating that the string is not a palindrome. If all pairs match, it returnstrue
. - Output: Based on the result from the
isPalindrome
function, the program prints whether the string is a palindrome or not.
How to Run the Program
- First, ensure that you have Go installed on your system. You can download it from here.
- Save the above code into a file named
palindrome.go
. - Open a terminal and navigate to the directory where the
palindrome.go
file is saved. - Run the following command to compile and execute the program:
go run palindrome.go
- After running the program, it will prompt you to enter a string. Type the string you want to check and press Enter.
- The program will output whether the string is a palindrome or not.