[Golang] Check Whether Two Strings Are Anagram of Each Other


Check whether two strings are anagram of each other in Go programming language.

Check by sorting [1]:

  1. sort both strings [3]
  2. compare the sorted strings

Another way to check anagram is by characters count, see [4].

Run Code on Go Playground

package anagram

import (
      "sort"
)

type ByRune []rune

func (r ByRune) Len() int           { return len(r) }
func (r ByRune) Swap(i, j int)      { r[i], r[j] = r[j], r[i] }
func (r ByRune) Less(i, j int) bool { return r[i] < r[j] }

func StringToRuneSlice(s string) []rune {
      var r []rune
      for _, runeValue := range s {
              r = append(r, runeValue)
      }
      return r
}

func AreAnagram(s1, s2 string) bool {
      var r1 ByRune = StringToRuneSlice(s1)
      var r2 ByRune = StringToRuneSlice(s2)

      sort.Sort(r1)
      sort.Sort(r2)

      return string(r1) == string(r2)
}

Testing:

package anagram

import (
      "testing"
)

func TestAreAnagram(t *testing.T) {
      if AreAnagram("listen", "silent") != true {
              t.Error(`"listen", "silent"`)
      }
      if AreAnagram("test", "ttew") != false {
              t.Error(`"test", "ttew"`)
      }
      if AreAnagram("geeksforgeeks", "forgeeksgeeks") != true {
              t.Error(`"geeksforgeeks", "forgeeksgeeks"`)
      }
      if AreAnagram("triangle", "integral") != true {
              t.Error(`"triangle", "integral"`)
      }
      if AreAnagram("abd", "acb") != false {
              t.Error(`"abd", "acb"`)
      }
}

Tested on:


References:

[1]Check whether two strings are anagram of each other - GeeksforGeeks
[2]sort - The Go Programming Language
[3][Golang] Sort String by Character
[4][Golang] Anagram Check by Characters Count