How to make two strings anagram by removing characters in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>
#include <math.h>

#define TOTAL_ABC_LETTERS 26

void RemoveByChar(char s[], char ch) {
    size_t len = strlen(s);

    for (int i = 0; i < len; i++) {
        if (s[i] == ch) {
            memmove(s + i, s + i + 1, len - i + 1);
        }
    }
}

void RemoveCharactersNeedToBeRemovedForAnagram(char str1[], char str2[]) {
    int count1[TOTAL_ABC_LETTERS] = { 0 }, count2[TOTAL_ABC_LETTERS] = { 0 };

    // count char frequency str1
    for (int i = 0; str1[i] != '\0'; i++)
        count1[str1[i] - 'a']++;

    // count char frequency str2
    for (int i = 0; str2[i] != '\0'; i++)
        count2[str2[i] - 'a']++;

    for (int i = 0; i < TOTAL_ABC_LETTERS; i++)
        if (abs(count1[i] - count2[i])) {
            RemoveByChar(str1, (char)(i + 'a'));
            RemoveByChar(str2, (char)(i + 'a'));
        }
}

int main()
{
    char str1[] = "masterfx", str2[] = "ksampret";

    RemoveCharactersNeedToBeRemovedForAnagram(str1, str2);

    puts(str1);

    puts(str2);
}




/*
run:

master
samret

*/

 



answered Sep 27, 2022 by avibootz

Related questions

1 answer 111 views
1 answer 115 views
1 answer 141 views
1 answer 140 views
1 answer 116 views
...