Go Practice Exercises

Palindrome Check in Go

Does the text read the same in both directions? Ignore spaces, punctuation and case.

  • Beginner
  • 3 min read
  • 1 runnable example
What you'll learn
  • Filtering letters
  • Lower case
  • Comparing from both ends
level
l0
e1
v2
e3
l4
The first and last letters match, then the next pair.

The same forwards and backwards

A palindrome reads the same in both directions, such as level. A good check ignores spaces, punctuation and the difference between upper and lower case.

The first loop keeps only letters and digits in lower case. The second compares the first character with the last, the second with the second to last, and so on, and stops at the first difference. %q prints the text with quotes.

Key points

  1. Keep only letters and digits.
  2. Compare in lower case.
  3. Stop at the first difference.

Runnable Go example

Go
Run code →
main.go
package main

import (
	"fmt"
	"strings"
	"unicode"
)

func isPalindrome(text string) bool {
	letters := []rune{}
	for _, r := range strings.ToLower(text) {
		if unicode.IsLetter(r) || unicode.IsDigit(r) {
			letters = append(letters, r)
		}
	}
	for i, j := 0, len(letters)-1; i < j; i, j = i+1, j-1 {
		if letters[i] != letters[j] {
			return false
		}
	}
	return true
}

func main() {
	for _, text := range []string{"level", "A man, a plan, a canal: Panama", "Go"} {
		fmt.Printf("%q -> %t\n", text, isPalindrome(text))
	}
}
Get a Run button for this example Result of running the code
"level" -> true
"A man, a plan, a canal: Panama" -> true
"Go" -> false

Practice

Open the example in the online compiler, change a value or add a line, and predict the output before you run it. Then break the code on purpose and read the compiler's message.

Finished this lesson?

Mark it as learned to track your progress.

Practice with a challenge

Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.

All challenges