Write a code to Check if two strings are Anagram or not

Anagram Check

        An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, using all the original letters exactly once. For example, the words "listen" and "silent" are anagrams of each other. Below, we'll explore the solutions in C, C++, Java, and Python.

What is an Anagram?

        Two strings are anagrams if they contain the same characters with the same frequencies, but in a different order.

Examples:

  • "listen" and "silent"

  • "triangle" and "integral"

Solutions:

Now let’s look at how to check if two strings are anagrams in different programming languages: Java, Python, C, and C++.

1. Java

        import java.util.Arrays;

        import java.util.Scanner;

        public class AnagramCheck {

            // Function to check if two strings are anagrams

            public static boolean areAnagrams(String str1, String str2) {

                // Remove all whitespace and convert strings to lowercase

                str1 = str1.replaceAll("\\s", "").toLowerCase();

                str2 = str2.replaceAll("\\s", "").toLowerCase();

                // Check if lengths are different

                if (str1.length() != str2.length()) {

                    return false;

                }

                // Convert strings to char arrays and sort

                char[] charArray1 = str1.toCharArray();

                char[] charArray2 = str2.toCharArray();

                Arrays.sort(charArray1);

                Arrays.sort(charArray2);

                // Check if sorted char arrays are equal

                return Arrays.equals(charArray1, charArray2);

            }        

            public static void main(String[] args) {

                Scanner scanner = new Scanner(System.in);

                System.out.print("Enter the first string: ");

                String str1 = scanner.nextLine();

                System.out.print("Enter the second string: ");

                String str2 = scanner.nextLine();

                // Check and print if the strings are anagrams

                if (areAnagrams(str1, str2)) {

                    System.out.println(str1 + " and " + str2 + " are anagrams.");

                } else {

                    System.out.println(str1 + " and " + str2 + " are not anagrams.");

                }

                scanner.close();

            }

        }

2. Python

        # Function to check if two strings are anagrams
        def are_anagrams(str1, str2):
            # Remove all whitespace and convert strings to lowercase
            str1 = str1.replace(" ", "").lower()
            str2 = str2.replace(" ", "").lower()

            # Check if lengths are different
            if len(str1) != len(str2):
                return False

            # Check if sorted characters are equal
            return sorted(str1) == sorted(str2)

        # Input from user
        str1 = input("Enter the first string: ")
        str2 = input("Enter the second string: ")

        # Check and print if the strings are anagrams
        if are_anagrams(str1, str2):
            print(f"{str1} and {str2} are anagrams.")
        else:
            print(f"{str1} and {str2} are not anagrams.")



3. C++

       #include <iostream>

        #include <algorithm>

        using namespace std;

        // Function to check if two strings are anagrams

        bool areAnagrams(string str1, string str2) {

            // Remove all whitespace and convert strings to lowercase

            str1.erase(remove_if(str1.begin(), str1.end(), ::isspace), str1.end());

            str2.erase(remove_if(str2.begin(), str2.end(), ::isspace), str2.end());

            transform(str1.begin(), str1.end(), str1.begin(), ::tolower);

            transform(str2.begin(), str2.end(), str2.begin(), ::tolower);

            // Check if lengths are different

            if (str1.length() != str2.length()) {

                return false;

            }

            // Sort the strings

            sort(str1.begin(), str1.end());

            sort(str2.begin(), str2.end());

            // Check if sorted strings are equal

            return str1 == str2;

        }

        int main() {

            string str1, str2;

            cout << "Enter the first string: ";

            getline(cin, str1);

            cout << "Enter the second string: ";

            getline(cin, str2);

            // Check and print if the strings are anagrams

            if (areAnagrams(str1, str2)) {

                cout << str1 << " and " << str2 << " are anagrams." << endl;

            } else {

                cout << str1 << " and " << str2 << " are not anagrams." << endl;

            }

            return 0;

        }


4. C 

        #include <stdio.h>

        #include <string.h>

        #include <ctype.h>

        // Function to check if two strings are anagrams

        int areAnagrams(char str1[], char str2[]) {

            // Function to remove spaces and convert to lowercase

            void formatString(char *str) {

                int i, j = 0;

                for (i = 0; str[i] != '\0'; i++) {

                    if (!isspace(str[i])) {

                        str[j++] = tolower(str[i]);

                    }

                }

                str[j] = '\0';

            }

            // Format the strings

            formatString(str1);

            formatString(str2);

            // Check if lengths are different

            if (strlen(str1) != strlen(str2)) {

                return 0;

            }

            // Sort the strings

            void sortString(char *str) {

                int n = strlen(str);

                for (int i = 0; i < n-1; i++) {

                    for (int j = i+1; j < n; j++) {

                        if (str[i] > str[j]) {

                            char temp = str[i];

                            str[i] = str[j];

                            str[j] = temp;

                        }

                    }

                }

            }

            sortString(str1);

            sortString(str2);

            // Check if sorted strings are equal

            return strcmp(str1, str2) == 0;

        }

        int main() {

            char str1[100], str2[100];

            printf("Enter the first string: ");

            gets(str1);

            printf("Enter the second string: ");

            gets(str2);

            // Check and print if the strings are anagrams

            if (areAnagrams(str1, str2)) {

                printf("%s and %s are anagrams.\n", str1, str2);

            } else {

                printf("%s and %s are not anagrams.\n", str1, str2);

            }

            return 0;

        }

Explanation of Code:

Each code version defines an areAnagrams function to determine if two strings are anagrams.

  • Format Strings: Remove whitespace and convert to lowercase.

  • Length Check: Ensure both strings have the same length.

  • Sorting: Sort the characters of both strings.

  • Comparison: Compare the sorted versions to check for equality.

Sample Input & Output:

Input:

  • str1 = "listen"

  • str2 = "silent"

Output: listen and silent are anagrams.

Input:

  • str1 = "hello"

  • str2 = "world"

Output: hello and world are not anagrams.

Conclusion:

Checking if two strings are anagrams is a common problem in programming that helps improve understanding of string manipulation, sorting, and character comparison in various programming languages.


**  Please do subscribe my blog for future updates and share with your friends, if you find this informative **

Comments

Popular Posts