Go Program to Check if Two Strings Are Anagrams

Introduction

An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. To determine if two strings are anagrams, you need to ensure that they contain the same characters in the same frequency, but possibly in a different order. This guide will demonstrate how to write a Go program that checks if two strings are anagrams.

Problem Statement

Create a Go program that:

  • Prompts the user to enter two strings.
  • Checks if the two strings are anagrams of each other.
  • Displays the result indicating whether the strings are anagrams.

Example:

  • Input: "listen", "silent"
  • Output: The strings are anagrams.

Solution Steps

  1. Import the fmt and strings Packages: Use import "fmt" for formatted I/O operations and import "strings" for string manipulation functions.
  2. Write a Function to Check if Two Strings Are Anagrams: Implement a function that sorts the characters of both strings and compares them.
  3. Write the Main Function: Define the main function, which is the entry point of every Go program.
  4. Prompt the User to Enter Two Strings: Use fmt.Scanln or fmt.Scanf to take input from the user.
  5. Call the Anagram Checking Function: Use the function to check if the two input strings are anagrams.
  6. Display the Result: Use fmt.Println to display whether the strings are anagrams.

Go Program

package main

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

// Step 2: Implement a function to check if two strings are anagrams
func areAnagrams(str1, str2 string) bool {
    // Remove spaces and convert strings to lower case for case insensitivity
    str1 = strings.ReplaceAll(str1, " ", "")
    str2 = strings.ReplaceAll(str2, " ", "")
    str1 = strings.ToLower(str1)
    str2 = strings.ToLower(str2)

    // If the lengths differ, they cannot be anagrams
    if len(str1) != len(str2) {
        return false
    }

    // Convert strings to slices of runes and sort them
    runeStr1 := []rune(str1)
    runeStr2 := []rune(str2)
    sort.Slice(runeStr1, func(i, j int) bool { return runeStr1[i] < runeStr1[j] })
    sort.Slice(runeStr2, func(i, j int) bool { return runeStr2[i] < runeStr2[j] })

    // Compare the sorted slices
    return string(runeStr1) == string(runeStr2)
}

/**
 * Go Program to Check if Two Strings Are Anagrams
 * Author: https://www.javaguides.net/
 */
func main() {
    // Step 4: Prompt the user to enter two strings
    var str1, str2 string
    fmt.Print("Enter the first string: ")
    fmt.Scanln(&str1)
    fmt.Print("Enter the second string: ")
    fmt.Scanln(&str2)

    // Step 5: Call the function to check if the strings are anagrams
    if areAnagrams(str1, str2) {
        // Step 6: Display the result
        fmt.Println("The strings are anagrams.")
    } else {
        fmt.Println("The strings are not anagrams.")
    }
}

Explanation

Step 2: Implement a Function to Check if Two Strings Are Anagrams

  • The areAnagrams function performs the following steps:
    • Removes spaces and converts both strings to lowercase to ensure case insensitivity and ignore spaces.
    • Compares the lengths of the two strings. If they differ, the strings cannot be anagrams.
    • Converts the strings into slices of runes, sorts the slices, and compares them. If the sorted strings are equal, the original strings are anagrams.

Step 4: Prompt the User to Enter Two Strings

  • The program prompts the user to enter two strings using fmt.Scanln.

Step 5: Call the Anagram Checking Function

  • The program calls the areAnagrams function to determine if the strings are anagrams.

Step 6: Display the Result

  • The program prints the result, indicating whether the strings are anagrams.

Output Example

Example 1:

Enter the first string: listen
Enter the second string: silent
The strings are anagrams.

Example 2:

Enter the first string: hello
Enter the second string: world
The strings are not anagrams.

Example 3 (with spaces and different cases):

Enter the first string: Conversation
Enter the second string: Voices Rant On
The strings are anagrams.

Conclusion

This Go program demonstrates how to check if two strings are anagrams by comparing their sorted characters. It covers basic programming concepts such as string manipulation, sorting, and function implementation in Go. This example is useful for beginners learning Go programming and understanding how to perform string-based operations effectively.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top