Adsense 728 * 15

Search

Custom Search

C Program to Check whether two Strings are Anagram of each other

Write a C program to check whether two strings are anagram of each other.  In this program, we write a code to take two input strings from a user and check whether two strings are anagram of each other.

Let's first understand what is an Anagram?

What is Anagram?

Two strings are said to be anagram, If both strings contain same characters, only the order of characters can be different.

For example -

i) "raj" and "jar" are anagram of each other.

ii) "abcde" and "dbaec" are anagram of each other.

Programming questions on strings

How to Check whether two Strings are Anagram of each other

Method 1

Use sorting, Sort both the strings and then compare. If both the strings are same then it's a anagram

Quicksort program in C, C++

Sorting algorithm and their time complexity

Method 2

Create hash and compare.

C Program to Check whether two Strings are Anagram of each other


C Program to Check whether two Strings are Anagram of each other


#include <stdio.h>
#include <string.h>

/* Check if both strings are anagrams */

int isAnagram(char str1[], char str2[]) {
 
      /* Default value assigned to zero */

      char str[256] = { 0 };
 
      /* Increment character count based on first string */

      for (int i = 0; i < strlen(str1); i++ ) {
  
           str[str1[i]]++;
      }
 
      /* Decrement character count based on second string */

      for (int j = 0; j < strlen(str2); j++ ) {
  
           str[str2[j]]--;
  
      }
 
        /* If both strings are anagrams 
           then net character count is zero */

      for (int k = 0; k < 256; k++ ) {

           if (str[k] != 0) {
    
               return 0;
           }
  
       }
 
      return 1;
}

int main(void) {

   char str1[100], str2[100];
 
   printf("\n Enter first string");
   gets(str1);
 
   printf("\n Enter second string");
   gets(str2);
 
   if (isAnagram(str1, str2)) {
  
      printf ("\n Enter strings are anagrams");
  
   } else {
  
     printf ("\n Enter strings are not anagrams");
   }
 
   return 0;
}



Output :

Enter first string  :  raj

Enter second string : jar

Enter strings are anagrams


Programming questions on Strings

Programming questions on Recursion

Programming questions on Array

Programming questions on Linked List

No comments:

Post a Comment