Check If Two Strings are Anagram in Go



In this tutorial, we will learn how to check if two strings are anagrams in Go. Anagrams are words or phrases that contain the same characters in the same quantity, but in a different order.


What is an Anagram

Anagrams are words or phrases formed by rearranging the letters of another word or phrase, using all the original letters exactly once. For example, 'listen' and 'silent' are anagrams.


Syntax

The syntax to check if two strings are anagrams in Go is:

import (
    "fmt"
    "sort"
    "strings"
)

func areAnagrams(s1, s2 string) bool {
    // Convert strings to []rune
    r1 := []rune(s1)
    r2 := []rune(s2)

    // Sort []rune slices
    sort.Slice(r1, func(i, j int) bool { return r1[i] < r1[j] })
    sort.Slice(r2, func(i, j int) bool { return r2[i] < r2[j] })

    // Compare sorted []rune slices
    return string(r1) == string(r2)
}


Example 1: Checking if two strings are anagrams

We can create a function to check if two given strings are anagrams by sorting their characters and comparing the sorted strings.

For example,

  1. Import the fmt, sort, and strings packages.
  2. Define a function named areAnagrams that takes two parameters s1 and s2 of type string and returns a bool.
  3. Convert the strings s1 and s2 into []rune slices.
  4. Sort the []rune slices using sort.Slice.
  5. Compare the sorted []rune slices converted back to strings.
  6. Return true if the strings are anagrams; otherwise, return false.
  7. In the main function, call the areAnagrams function with sample strings and print the result.

Go Program

package main

import (
    "fmt"
    "sort"
    "strings"
)

func areAnagrams(s1, s2 string) bool {
    // Convert strings to []rune
    r1 := []rune(s1)
    r2 := []rune(s2)

    // Sort []rune slices
    sort.Slice(r1, func(i, j int) bool { return r1[i] < r1[j] })
    sort.Slice(r2, func(i, j int) bool { return r2[i] < r2[j] })

    // Compare sorted []rune slices
    return string(r1) == string(r2)
}

func main() {
    // Sample strings
    str1 := "listen"
    str2 := "silent"

    // Check if the strings are anagrams
    if areAnagrams(str1, str2) {
        fmt.Printf("%s and %s are anagrams\n", str1, str2)
    } else {
        fmt.Printf("%s and %s are not anagrams\n", str1, str2)
    }
}

Output

listen and silent are anagrams