How to check if two strings are anagrams (same letters, different words) in C

2 Answers

0 votes
#include <stdio.h>
#include <ctype.h>

#define ASCII_RANGE 256

int areAnagrams(const char s1[], const char s2[]) {
    int freq[ASCII_RANGE] = {0};

    /* Count characters from first string */
    for (int i = 0; s1[i] != '\0'; i++) {
        unsigned char c = (unsigned char)s1[i];
        freq[c]++;
    }

    /* Subtract characters from second string */
    for (int i = 0; s2[i] != '\0'; i++) {
        unsigned char c = (unsigned char)s2[i];
        freq[c]--;
    }

    /* If all counts return to zero, they match */
    for (int i = 0; i < ASCII_RANGE; i++) {
        if (freq[i] != 0) {
            return 0;
        }
    }

    return 1;
}

int main(void) {
    char s1[32] = "stdoi";
    char s2[32] = "iostd";

    if (areAnagrams(s1, s2))
        printf("Anagram\n");
    else
        printf("Not anagram\n");

    return 0;
}



/*
run:

Anagram

*/

 



answered Jan 27, 2019 by avibootz
edited Aug 20 by avibootz
0 votes
#include <stdio.h>
#include <string.h>
#include <ctype.h>

#define ASCII_RANGE 256

// Check whether two strings are anagrams (case-insensitive)
int areAnagrams(const char *str1, const char *str2) {
    int freq[ASCII_RANGE] = {0};

    size_t len1 = strlen(str1);
    size_t len2 = strlen(str2);

    // If lengths differ, they cannot be anagrams
    if (len1 != len2) {
        return 0;
    }

    // Count characters from the first string
    for (size_t i = 0; i < len1; i++) {
        unsigned char ch = (unsigned char)tolower(str1[i]);
        freq[ch]++;
    }

    // Subtract characters from the second string
    for (size_t i = 0; i < len2; i++) {
        unsigned char ch = (unsigned char)tolower(str2[i]);
        freq[ch]--;
        if (freq[ch] < 0) {
            return 0; // mismatch detected
        }
    }

    return 1; // strings are anagrams
}

int main(void) {
    char str1[32] = "stdoi";
    char str2[32] = "iostd";

    if (areAnagrams(str1, str2)) {
        printf("The strings are anagrams.\n");
    } else {
        printf("The strings are NOT anagrams.\n");
    }

    return 0;
}


/*
run:

The strings are anagrams.

*/

 



answered Nov 12, 2025 by avibootz
edited Aug 20 by avibootz
...