TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

Program to Determine Whether Two Strings are The Anagram

Program to Determine Whether Two Strings are The Anagram on fibonacci, factorial, prime, armstrong, swap, reverse, search, sort, stack, queue, array, linkedlist, tree, graph etc.

<< Back to PROGRAM

Q. Program to determine whether two strings are the anagram

Two Strings are called the anagram if they contain the same characters. However, the order or sequence of the characters can be different. In this program, our task is to check for two strings that, they are the anagram or not. For this purpose, we are following a simpler approach. First of all, Compare the length of the strings, if they are not equal in the length then print the error message and make an exit, otherwise, convert the string into lower-case for the easy comparisons. Sort both the strings using bubble sort or other sorting methods. If the strings are found to be identical after sorting, then print that strings are anagram otherwise print that strings are not the anagram.

Algorithm

  1. Define two strings.
  2. Check for their lengths. If the lengths are not equal, then strings are not an anagram.
  3. Else, convert the string to lower case character to make the comparison easy.
  4. Some language allows the strings to provide inbuilt function for sorting of string. If not then convert them to character array for sorting.
  5. Sort the array.
  6. Finally, check for the equality of content.

Solution

Python

str1 = "Grab";
str2 = "Brag"; 
#Checking for the length of strings
if(len(str1)!= len(str2)):
    print ("Both the strings are not anagram");
else:
    #Converting the strings to lower case
    str1 = str1.lower();
    str2 = str2.lower();
    #Sorting the strings
    str1 = ''. join(sorted(str1));
    str2 = ''. join(sorted(str2));
    
    if (str1 == str2):
        print ("Both the strings are anagram"); 
    else:
        print ("Both the strings are not anagram");

Output:

Both the strings are anagram.

C

#include <stdio.h>
#include <string.h>
void toLowercase(char[]);
void sortArray(char[]);
int main ()
{
    char str1[] = "Grab", str2[] = "Brag";
    int i, j = 0;
    
    //Checking for the length of strings
    if(strlen(str1) != strlen(str2)){
        printf("Both the strings are not anagram");
        return 0;
    }
    else {
    //converting the string to lowercase
    toLowercase(str1);
    toLowercase(str2);
    
    //Sorting the arrays by making call to user defined function sortArray()
    sortArray(str1);
    sortArray(str2);
    
    for(i = 0; i < strlen(str1); i++){
       if(str1[i] != str2[i]){
           printf("Both the strings are not anagram");
           return 0;
       } 
    }   
    printf("Both the strings are anagram");
    }
    return 0;
}
void toLowercase(char a[]){
            int i;
            for(i = 0; i < strlen(a)-1; i++){
                a[i] = a[i]+32;
            }    
        }
 void sortArray(char a[]){
            int temp = 0,i,j;
            for(i = 0; i < strlen(a)-1; i++){
                for (j = i+1; j < strlen(a); j++){
                if(a[i] > a[j]) {
                    temp = a[i];
                    a[i] = a[j];
                    a[j] = temp;       
                    }
                }
            }   
        }

Output:

Both the strings are anagram.

JAVA

import java.util.Arrays;
public class Anagram {    
    public static void main (String [] args) {        
        String str1="Brag";
        String str2="Grab";
        
        //Converting both the string to lower case.
        str1 = str1.toLowerCase();
        str2 = str2.toLowerCase();
        
        //Checking for the length of strings
        if (str1.length() != str2.length()) {
            System.out.println("Both the strings are not anagram");
        }
        else {
            //Converting both the arrays to character array
            char[] string1 = str1.toCharArray();
            char[] string2 = str2.toCharArray();
            
            //Sorting the arrays using in-built function sort ()
            Arrays.sort(string1);
            Arrays.sort(string2);
            
            //Comparing both the arrays using in-built function equals ()
            if(Arrays.equals(string1, string2) == true) {
                System.out.println("Both the strings are anagram");
            }
            else {
                System.out.println("Both the strings are not anagram");
            }
        }
    }
}

Output:

Both the strings are anagram.

C#

using System;
public class Program
{
    public static void Main ()
    {
        string str1="Brag";
        string str2="Grab";
        
        //Converting both the string to lower case and then removing white spaces.
        str1 = str1.ToLower();
        str2 = str2.ToLower();
        
        //Checking for the length of strings
        if(str1.Length != str2.Length) {
            Console.WriteLine("Both the strings are not anagram");
        }
 
        else { 
            //Converting both the arrays to character array
            char[] string1 = str1.ToCharArray();
            char[] string2 = str2.ToCharArray();
            
            //Sorting the arrays using in-built function sort ()
            Array.Sort(string1);
            Array.Sort(string2);
            
            //Comparing both the strings using in-built function equals ()
            if(string1.ToString().Equals(string2.ToString())) {
                Console.WriteLine("Both the strings are anagram");
            }
            else {
                Console.WriteLine("Both the strings are not anagram");
            }
        }
    }
}

Output:

Both the strings are anagram.

PHP

<!DOCTYPE html>
<html>
<body>
<?php
    $str1 = "Grab";
    $str2 = "Brag";
    
    //Checking for the length of strings
    if(strlen($str1) != strlen($str2)){
        echo "Both the strings are not anagram";
    }
    else{
        //Convert strings to lower case
        $str1 = strtolower($str1);
        $str2 = strtolower($str2);
    
        //Splitting the array to convert it into array
        $str1array = str_split($str1);
        $str2array = str_split($str2);
    
        //Sorting arrays of character
        sort($str1array);
        sort($str2array);
    
        //Joining the characters from array to convert it into single string
        $str1 = implode("",$str1array);
        $str2 = implode("",$str2array);

        //Comparing two strings, it returns 0 when the strings are equal else -1
        if(strcmp($str1,$str2) == 0){
            echo "Both the strings are anagram";
        }
        else{
            echo "Both the strings are not anagram";
        }
    }
?>
</body>
</html>

Output:

Both the strings are anagram.

Next TopicPrograms List




Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf