Go Program: Check if Two Strings are Anagrams
This Go program checks if two strings are anagrams. Two strings are considered anagrams if they contain the same characters but in different orders.
Program Structure
- Import Packages: We import the
fmt
package for input and output functions. - Function
areAnagrams
: This function checks if two strings are anagrams. - Main Function: This function reads input from the user, calls
areAnagrams
, and prints the result.
Go Program Code
package main
import (
"fmt"
"strings"
"sort"
)
// areAnagrams checks if two strings are anagrams
// It returns true if they are anagrams, otherwise false
func areAnagrams(str1, str2 string) bool {
// Remove spaces and convert to lowercase
str1 = strings.ToLower(strings.ReplaceAll(str1, " ", ""))
str2 = strings.ToLower(strings.ReplaceAll(str2, " ", ""))
// If lengths differ, they cannot be anagrams
if len(str1) != len(str2) {
return false
}
// Convert strings to slices of runes
runes1 := []rune(str1)
runes2 := []rune(str2)
// Sort the runes
sort.Slice(runes1, func(i, j int) bool {
return runes1[i] < runes1[j]
})
sort.Slice(runes2, func(i, j int) bool {
return runes2[i] < runes2[j]
})
// Compare sorted slices
for i := range runes1 {
if runes1[i] != runes2[i] {
return false
}
}
return true
}
func main() {
var str1, str2 string
fmt.Println("Enter the first string:")
fmt.Scanln(&str1)
fmt.Println("Enter the second string:")
fmt.Scanln(&str2)
if areAnagrams(str1, str2) {
fmt.Println("The strings are anagrams.")
} else {
fmt.Println("The strings are not anagrams.")
}
}
Explanation:
- Import Packages: The
fmt
package is used for reading input and printing output, whilestrings
andsort
packages help with string manipulation and sorting. - Function
areAnagrams
:- Removes spaces and converts strings to lowercase.
- Checks if the lengths are different; if so, they can’t be anagrams.
- Converts the strings to slices of runes, sorts them, and compares them.
- Main Function:
- Reads two strings from the user.
- Calls
areAnagrams
to check if they are anagrams. - Prints the result.
The main
function handles user input and output. It prompts the user to enter two strings, calls areAnagrams
, and displays whether the strings are anagrams.