How to remove odd frequency characters from a string in C

1 Answer

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

#define MAX_CHAR 256

void removeOddFrequencyChars(char *str) {
    int freq[MAX_CHAR] = {0};
    int len = strlen(str);

    // Count frequency of each character
    for (int i = 0; i < len; i++) {
        freq[(int)str[i]]++;
    }

    // Construct new string with only even frequency characters
    int index = 0;
    for (int i = 0; i < len; i++) {
        if (freq[(int)str[i]] % 2 == 0) {
            str[index++] = str[i];
        }
    }
    str[index] = '\0'; // Null-terminate the new string
}

int main() {
    char str[] = "c programming version 23";
    
    removeOddFrequencyChars(str);
    
    printf("%s\n", str);
    
    return 0;
}

 

/*
run:

ogmmingion

*/
 

 



answered Nov 19, 2024 by avibootz

Related questions

1 answer 225 views
1 answer 121 views
1 answer 130 views
1 answer 118 views
1 answer 108 views
1 answer 115 views
...