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...

How to remove the first character of a string in Golang

How to remove the first character of a string in Golang

Learn how to remove first the character of a string in GoLang

Go Strings Cheat Sheet Part 1

Go Strings Cheat Sheet Part 1

Learn the Basic of Working with GoLang Strings.

How to Convert GoLang Integer to String Conversion

How to Convert GoLang Integer to String Conversion

Learn how to convert integers to strings and how to convert strings to integers in GoLang