×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

C program to check two strings are anagram or not

Here, we are going to learn how to check whether two strings are anagram or not in C programming language?
Submitted by Nidhi, on July 20, 2021

Problem statement

Read two strings from the user and check whether the given strings are anagram or not using C program.

Note: If two strings contain the same characters in different order is known as an anagram of string.

C program to check two strings are anagram or not

The source code to check two strings are anagram or not is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// C program to check two strings are anagram or not

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

int checkAnagram(char* str1, char* str2)
{

    int tmp1[26] = { 0 };
    int tmp2[26] = { 0 };

    int i = 0;

    while (str1[i] != '\0') {
        tmp1[str1[i] - 'a'] = tmp1[str1[i] - 'a'] + 1;
        i++;
    }

    i = 0;
    while (str2[i] != '\0') {

        tmp2[str2[i] - 'a'] = tmp2[str2[i] - 'a'] + 1;
        i++;
    }

    for (i = 0; i < 26; i++) {
        if (tmp1[i] != tmp2[i])
            return 0;
    }
    return 1;
}

int main()
{
    char str1[32];
    char str2[32];

    printf("Enter string1: ");
    scanf("%s", str1);

    printf("Enter string2: ");
    scanf("%s", str2);

    if (checkAnagram(str1, str2))
        printf("Strings are anagram\n");
    else
        printf("Strings are not anagram\n");

    return 0;
}

Output

RUN 1:
Enter string1: silent
Enter string2: listen
Strings are anagram

RUN 2:
Enter string1: integral
Enter string2: triangel
Strings are anagram

RUN 3:
Enter string1: abcd
Enter string2: abbd
Strings are not anagram

Explanation

In the above program, we created two functions checkAnagram() and main(). The checkAnagram() function is used to find two strings are anagram or not.

In the main() function, we read two strings from the user and called the checkAnagram() function to check strings are anagram or not and print the appropriate message on the console screen.

C String Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.