ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

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 Solution:

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.

Program:

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 »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.