Q:

C program to check two strings are anagram or not

0

C program to check two strings are anagram or not

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now