Go Program to Check if Two Strings Are Anagrams

1. Introduction

Anagrams are words or phrases that are formed by rearranging the letters of another word or phrase, using all the original letters exactly once. They have been a popular topic in literature and word games. In this blog post, we will explore a Go program that checks if two strings are anagrams of each other.

2. Program Overview

The basic idea to determine if two strings are anagrams is to check if both have the same characters with the same frequency. Our Go program will:

1. Take two strings as input.

2. Check if they are anagrams.

3. Display the result to the user.

3. Code Program

// Declare the package name
package main

// Import the necessary packages
import (
	"fmt"
	"strings"
	"sort"
)

// Function to check if two strings are anagrams
func areAnagrams(str1, str2 string) bool {
    // Convert strings to lowercase for case-insensitive comparison
    s1 := strings.ToLower(str1)
    s2 := strings.ToLower(str2)

    // Sort the strings
    s1Slice := strings.Split(s1, "")
    s2Slice := strings.Split(s2, "")
    sort.Strings(s1Slice)
    sort.Strings(s2Slice)
    
    // Check if sorted strings are equal
    return strings.Join(s1Slice, "") == strings.Join(s2Slice, "")
}

// Main function
func main() {
	var str1, str2 string

	fmt.Print("Enter first string: ")
	fmt.Scanln(&str1)
	fmt.Print("Enter second string: ")
	fmt.Scanln(&str2)

	if areAnagrams(str1, str2) {
		fmt.Println("The strings are anagrams!")
	} else {
		fmt.Println("The strings are not anagrams!")
	}
}

Output:

For the input strings "listen" and "silent":
Enter first string: listen
Enter second string: silent
The strings are anagrams!

4. Step By Step Explanation

1. Setting Up: We start by specifying the package and importing the required libraries.

2. Anagram Checker Function: The areAnagrams function first converts the strings to lowercase for a case-insensitive comparison. It then sorts the characters of each string and compares if they are the same.

3. User Interaction: The main function prompts the user to enter two strings. It then checks if the two strings are anagrams using the areAnagrams function and displays the result.

By using this program, you can quickly verify if two words or phrases are anagrams, providing both fun and utility in word games and linguistic explorations.

Comments