golang palindrome
To check if a string is a palindrome in Go (Golang), follow these steps:
- Import the necessary packages:
import (
"fmt"
"strings"
)
The fmt
package is needed for reading input and printing output, while the strings
package provides utility functions for manipulating strings.
- Read the input string:
var input string
fmt.Print("Enter a string: ")
fmt.Scan(&input)
This prompts the user to enter a string and stores it in the input
variable.
- Remove any spaces from the input string:
input = strings.ReplaceAll(input, " ", "")
This line removes any spaces from the input string using the ReplaceAll
function from the strings
package.
- Initialize two pointers,
start
andend
, pointing to the start and end of the string:
start := 0
end := len(input) - 1
- Check if the string is a palindrome using a loop:
isPalindrome := true
for start < end {
if input[start] != input[end] {
isPalindrome = false
break
}
start++
end--
}
In each iteration of the loop, it compares the characters at the start
and end
positions. If they are not equal, it sets the isPalindrome
variable to false
and breaks out of the loop.
- Print the result:
if isPalindrome {
fmt.Println("The string is a palindrome.")
} else {
fmt.Println("The string is not a palindrome.")
}
This code uses conditional statements to print whether the string is a palindrome or not based on the value of the isPalindrome
variable.
That's it! The code above checks if a string is a palindrome in Go without using any personal words or sentences.