How to check if a string is a palindrome in Golang?

To check if a string is a palindrome in Golang, you can follow these steps:

  1. Import the strings package for manipulating strings:
import "strings"
  1. Define a function that takes a string as input and returns a boolean value indicating whether it is a palindrome:
func isPalindrome(str string) bool { // Convert the string to lowercase and remove any non-alphanumeric characters str = strings.ToLower(str) str = removeNonAlphanumeric(str) // Check if the reversed string is equal to the original string return str == reverseString(str) }
  1. Define a helper function to reverse the input string:
func reverseString(str string) string { reversed := "" for i := len(str) - 1; i >= 0; i-- { reversed += string(str[i]) } return reversed }
  1. Define a helper function to remove non-alphanumeric characters from the input string:
func removeNonAlphanumeric(str string) string { var sb strings.Builder for _, char := range str { if (char >= 'a' && char <= 'z') || (char >= '0' && char <= '9') { sb.WriteRune(char) } } return sb.String() }
  1. Test the function with different strings:
func main() { testString := "A man, a plan, a canal: Panama" if isPalindrome(testString) { fmt.Println("The string is a palindrome") } else { fmt.Println("The string is not a palindrome") } }

In this example, the function will output "The string is a palindrome" because the test string "A man, a plan, a canal: Panama" is a palindrome. However, keep in mind that the solution may vary depending on how you define a palindrome (e.g., consider case sensitivity and whitespace handling).