C

How To Check If Two Strings Are Anagrams In C

In this tutorial, we are going to see how to check if the two strings are anagrams or not in C. Two strings form an anagram, if and only if they contain the same number of characters, the order of the characters does not matter. If two strings are anagrams, one string can be rearranged to form the other string. For example:

  • abc and cba are anagrams.
  • listen and silent are also anagrams

 

 

Anagram program in C
#include <stdio.h>
 
int isAnagram(char str1[], char str2[])
{
  int arr1[26] = {0}, arr2[26] = {0}, i=0;
 
  while (str1[i] != '\0')
  {
    arr1[str1[i]-'a']++;
    i++;
  }
 
  i = 0;
 
  while (str2[i] != '\0')
  {
    arr2[str2[i]-'a']++;
    i++;
  }
 
  for (i = 0; i < 26; i++)
  {
    if (arr1[i] != arr2[i])
      return 0;
  }
 
  return 1;
}
 
int main()
{
  char str1[100], str2[100];

  printf("Enter the first string: ");
  gets(str1);

  printf("Enter the second string: ");
  gets(str2);

  if (isAnagram(str1, str2) == 1)
    printf("The strings are anagrams.\n");
  else
    printf("The strings are not anagrams.\n");

  return 0;
}

Output:

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

 

mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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