Is String a Palindrome?

Is String a Palindrome?

Learn How to Test if a String is a Palindrome in Go.

In this short tutorial, we'll learn how to check if a string is a palindrome or not using Go (GoLang).

Is Palindrome

Here is the code example of how to check if a string is a palindrome:

package strings

func IsPalindrome(input string) bool {

	// If the input string length is equal to 1 it's a Palindrome.
	if len(input) == 1 {
		return true
	}

	// Reverse the input string.
	rev := Reverse(input)

	// Check if the input string and rev string are equal.
	if input == rev {
		return true
	}

	return false
}

Reverse String

Here is the code example of how to reverse a string:

package strings

func Reverse(str string) string {

	// Create a slice of runes.
	r := []rune(str)

	// Beginning index of rune slice.
	var beg int

	// Ending index of the rune slice.
	end := len(r) - 1

	// Loop until bd and end meet in the middle of the slice.
	for beg < end {

		// Swap rune
		temp := r[beg]
		r[beg] = r[end]
		r[end] = temp

		beg = beg + 1
		end = end - 1
	}

	return string(r)
}

Testing

Testing our code is an essential skill and is a habit that every developer should get into doing.

Here is the example test code:

package strings

import "testing"

func TestIsPalindrome(t *testing.T) {
	// Test table of strings.
	palindromeTests := []struct {
		name     string
		input    string
		expected bool
	}{
		{"bob", "bob", true},
		{"salas", "salas", true},
		{"eve", "eve", true},
	}

	// Loop over all test.
	for _, tt := range palindromeTests {
		var got = IsPalindrome(tt.input)
		if got {
			t.Log("Is Palindrome")
		} else {
			t.Fatalf("Got %v, Expected %v.", got, tt.expected)
		}
	}
}

Source Code

You can find the source code here: GitHub

Did you like it? Why don't you try also...

Using Makefiles For Go (GoLang) Development

Using Makefiles For Go (GoLang) Development

Learn how to run, build and, compile Go (GoLang) Applications for any Platform and Operating System using a Makefile

Sorting Slices In Go

Sorting Slices In Go

Learn How To Sort Slices in GoLang

Reverse Strings in Go

Reverse Strings in Go

Learn How To Reverse Strings in GoLang