C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Strings in C

Check anagram strings

C Program: Check Whether Two Strings Are Anagrams

C

#include <stdio.h>

#include <string.h>

#include <ctype.h>

 

int main() {

    char str1[100], str2[100];

    int freq1[256] = {0}, freq2[256] = {0};

    int i;

 

    // Input two strings

    printf("Enter first string: ");

    fgets(str1, sizeof(str1), stdin);

    printf("Enter second string: ");

    fgets(str2, sizeof(str2), stdin);

 

    // Remove newline characters from input

    str1[strcspn(str1, "\n")] = '\0';

    str2[strcspn(str2, "\n")] = '\0';

 

    // If lengths differ, they can't be anagrams

    if (strlen(str1) != strlen(str2)) {

        printf("Strings are NOT anagrams.\n");

        return 0;

    }

 

    // Convert both to lowercase and count character frequencies

    for (i = 0; str1[i] != '\0'; i++) {

        freq1[(unsigned char)tolower(str1[i])]++;

        freq2[(unsigned char)tolower(str2[i])]++;

    }

 

    // Compare frequencies

    for (i = 0; i < 256; i++) {

        if (freq1[i] != freq2[i]) {

            printf("Strings are NOT anagrams.\n");

            return 0;

        }

    }

 

    printf("Strings are ANAGRAMS of each other.\n");

    return 0;

}

Output

 
OUTPUT 1 :
Enter first string: Listen
Enter second string: Silent
Strings are ANAGRAMS of each other.

OUTPUT 2 :
Enter first string: Hello
Enter second string: World
Strings are NOT anagrams.

Explanation

  • Two strings are anagrams if they contain the same characters in any order (e.g., listen and silent).
  • Steps:
    1. Input two strings using fgets().
    2. Remove newline characters.
    3. Convert all letters to lowercase for uniform comparison.
    4. Use frequency arrays freq1[] and freq2[] to count occurrences of each character.
    5. Compare both arrays — if all frequencies match, the strings are anagrams.