• Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard
CSEstack

What do you want to Learn Today?

  • Programming
    • Tutorial- C/C++
    • Tutorial- Django
    • Tutorial- Git
    • Tutorial- HTML & CSS
    • Tutorial- Java
    • Tutorial- MySQL
    • Tutorial- Python
    • Competitive Coding Challenges
  • CSE Subject
    • (CD) Compiler Design
    • (CN) Computer Network
    • (COA) Computer Organization & Architecture
    • (DBMS) Database Management System
    • (DS) Data Structure
    • (OS) Operating System
    • (ToA) Theory of Automata
    • (WT) Web Technology
  • Interview Questions
    • Interview Questions- Company Wise
    • Interview Questions- Coding Round
    • Interview Questions- Python
    • Interview Questions- REST API
    • Interview Questions- Web Scraping
    • Interview Questions- HR Round
    • Aptitude Preparation Guide
  • GATE 2022
  • Linux
  • Trend
    • Full Stack Development
    • Artificial Intelligence (AI)
    • BigData
    • Cloud Computing
    • Machine Learning (ML)
  • Write for Us
    • Submit Article
    • Submit Source Code or Program
    • Share Your Interview Experience
  • Tools
    • IDE
    • CV Builder
    • Other Tools …
  • Jobs

[Program] How to Check if Two Strings are Anagrams in C?

Aniruddha Chaudhari/18783/2
C / C++Code

Before writing code to check if two strings are anagrams in C, let’s understand- what is the anagram of the string?

Table of Contents

  • What is Anagram of the string?
  • Program to Check if Two Strings are Anagrams in C
    • 1. by using Quick Sort
    • 2. by counting each elements

What is Anagram of the string?

An anagram of the string is the string, obtained by rearranging the letters of the source string.

Example:

Source String: csestack
Anagram of source String: cesstack

The second and third letters of the source string are altered, giving an anagram of the string.

Properties of Anagram String:

  • One string may have multiple anagrams.
  • Every string is anagram if itself.
  • If one string is the anagram of other string, both the strings have equal length. This is the first condition you should check for anagrams.

In C, you can check the length of the string using the strlen() function.

Program to Check if Two Strings are Anagrams in C

There are two approaches to check if the two strings are anagrams of each other or not.

1. by using Quick Sort

  • Sort the String using quicksort (both strings)
  • After sorting, check if two strings are identical or not
  • If two strings are identical then these two strings are anagrams of each other.
  • If not identical, these two strings are not anagrams of each other.
#include<stdio.h>
#include<stdbool.h>
#include<string.h>
 
/* Function prototype 
for sorting a given string using quick sort */
void quickSort(char *nArr, int nSI, int nEI);
 
/* function to check 
whether two strings are anagram of each other */
bool checkAnagram(char *strTest1, char *strTest2)
{
 int i =0; 
 // Get lengths of both strings
 int nLen1 = strlen(strTest1);
 int nLen2 = strlen(strTest2);
 
 // If length of two strings are different, 
 // these are not anagram
  
 if (nLen1 != nLen2)
 return false;
 
 // Sort both strings using quick sort
 quickSort (strTest1, 0, nLen1 - 1);
 quickSort (strTest2, 0, nLen2 - 1);
 
 // Compare both the sorted strings
 for (i = 0; i < nLen1; i++)
   if (strTest1[i] != strTest2[i])
     return false;
 
 return true;
}
 
// Following functions 
//(exchange and partition are needed for quickSort)
void swapElement(char *a, char *b)
{
 char temp;
 temp = *a;
 *a = *b;
 *b = temp;
}
//Partition string into two string using pivot element
int partitionPivot(char nArr[], int nSI, int nEI)
{
 char x = nArr[nEI];
 int i = (nSI - 1);
 int j;
 
 for (j = nSI; j <= nEI - 1; j++)
 {
   if(nArr[j] <= x)
   {
     i++;
     swapElement(&nArr[i], &nArr[j]);
   }
 }
 
 swapElement(&nArr[i + 1], &nArr[nEI]);
 return (i + 1);
}
 
/* Quick Sort Implementation 
nArr[] : int Array to be sorted
nSI : Starting index of String
nEI : Ending index of String
nPI : Partitioning index (Pivot Index)
*/
 
void quickSort(char nArr[], int nSI, int nEI)
{
 int nPI; 
 if(nSI < nEI)
 {
   nPI = partitionPivot(nArr, nSI, nEI);
   quickSort(nArr, nSI, nPI - 1);
   quickSort(nArr, nPI + 1, nEI);
 }
}
 
int main()
{
 char strTest1[] = "csestack";
 char strTest2[] = "cesstack";
 if (checkAnagram(strTest1, strTest2) )
 printf("The two strings are anagram of each other");
 else
 printf("The two strings are not anagram of each other");
 
 return 0;
}

Output:

The two strings are an anagram of each other

For practice, you can solve the problem using any other popular sorting algorithms.

2. by counting each elements

  • Create two arrays of size 26 to save elements count for each letter
  • Scan first string and count number of times each unique element is repeated. Save count for each letter  in the first array
  • Repeat the same procedure for the second string.
  • Match the two array to check the count for each unique element.
  • If it is the same for both strings, two strings are an anagram of each other.
  • If there is a mismatch for any unique element count, these two strings are not an anagram of each other.
#include<stdio.h>
#include<stdbool.h>
#include<string.h>
 
# define NO_OF_CHARS 26
 
/* function to check whether
two strings are anagram of each other */
bool checkAnagram(char *strTest1, char *strTest2)
{
  // Create two count arrays and initialize all values as 0
  int nCount1[NO_OF_CHARS] = {0};
  int nCount2[NO_OF_CHARS] = {0};
  int i=0;
 
  if (strlen(strTest1) != strlen(strTest2))
    return false;
  // For each character in input strings,
  // increment count in
  // corresponding count array
  //97 is ascii value of 'a'
  for (i = 0; strTest1[i] && strTest2[i]; i++)
  {
    nCount1[strTest1[i]-97]++;
    nCount2[strTest2[i]-97]++;
  }
 
  // Compare count arrays
  for (i = 0; i < NO_OF_CHARS; i++)
    if (nCount1[i] != nCount2[i])
      return false;
 
  return true;
}
 
/* Driver program to test to pront printDups*/
int main()
{
  char strTest1[] = "csestack";
  char strTest2[] = "stackcse";
 
  if (checkAnagram(strTest1, strTest2))
    printf("The two strings are anagram of each other");
 
  else
    printf("The two strings are not anagram of each other");
 
  return 0;
}

Output:

The two strings are anagram of each other.

This is one of the coding questions asked in the interview. If you are preparing for the job, practice solving these coding interview questions.

This is all about the program to check if two strings are anagrams in C. If you find any other better way of solving the same problem, let’s discuss it in the comment.

c-string
Aniruddha Chaudhari
I am complete Python Nut, love Linux and vim as an editor. I hold a Master of Computer Science from NIT Trichy. I dabble in C/C++, Java too. I keep sharing my coding knowledge and my own experience on CSEstack.org portal.

Your name can also be listed here. Got a tip? Submit it here to become an CSEstack author.

Comments

  • Reply
    Anand
    February 1, 2018 at 10:09 pm

    The Coding style is absolutely awesome ans easy to understand..I like this code ..

    • Reply
      Aniruddha Chaudhari
      February 2, 2018 at 12:09 am

      Thanks, Anand.

Leave a Reply Cancel reply

C Programming

  1. C- Introduction
  2. C- Compile & Execute Program
  3. C- Data Types
  4. C- if-else statement
  5. C- While, do-while, for loop
  6. C- Array
  7. C- Function (Types/Call)
  8. C- strlen() vs sizeof()
  9. C- Nested Switch Statement
  10. C- Recursion
  11. C- Dynamic Programming
  12. C- Storage Classes
  13. C- Creating Header File
  14. C- Null Pointer
  15. C- Stack and Queue
  16. C- Implement Stack using Array
  17. C- Implement Linked List in C
  18. C- File Handling
  19. C- Makefile Tutorial

Object Oriented Concepts in C++

  • C++: C vs OOPs Language
  • C++: Introduction to OOPs Concepts
  • C++: Inheritance

Sorting Algorithms

  • Different Types of Sorting Algo
  • Selection Sort
  • Bubble Sort
  • Quick Sort

Programming for Practice

  1. Online C/C++ Compiler

String Handling:

  1. Remove White Spaces from String
  2. Implement strstr Function in C
  3. Convert String to Int – atoi()
  4. Check if String is Palindrome
  5. Check if Two Strings are Anagram
  6. Split String in using strtok_r()
  7. Undefined reference to strrev

Array:

  1. Check if Array is Sorted

Bit Manipulation:

  1. Count Number of 1’s in Binary

Linked List:

  1. Reverse a Linked List Elements

Number System:

  1. Program to Find 2’s Complement
  2. Convert Decimal to Binary in C

Tricky Questions:

  1. Add Two Numbers without Operator
  2. Find Next Greater Number
  3. Swap values without temp variable
  4. Print 1 to 100 without Loop

Interview Coding Questions

  • 50+ Interview Coding Questions

© 2022 – CSEstack.org. All Rights Reserved.

  • Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard