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,
- Import the
fmt
,sort
, andstrings
packages. - Define a function named
areAnagrams
that takes two parameterss1
ands2
of typestring
and returns abool
. - Convert the strings
s1
ands2
into[]rune
slices. - Sort the
[]rune
slices usingsort.Slice
. - Compare the sorted
[]rune
slices converted back to strings. - Return
true
if the strings are anagrams; otherwise, returnfalse
. - 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