How to remove non-duplicate characters from string in C

1 Answer

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

char* removeNonDuplicate(char* str) {
    char arr[256] = "";
    int size = strlen(str);
    
    strcpy(arr, str);
    
    char duplicateArray[256];
    
    int duplicateIndex = 0;
    for (int i = 0; i < size; i++) {
        int firstIndex = -1;
        int lastIndex = -1;
        for (int j = 0; j < size; j++) {
            if (arr[i] == arr[j]) {
                if (firstIndex == -1) {
                    firstIndex = j;
                }
                lastIndex = j;
            }
        }
        if (firstIndex != lastIndex) {
            duplicateArray[duplicateIndex] = arr[i];
            duplicateIndex++;
        }
    }
    
    duplicateArray[duplicateIndex] = '\0';
    char* result = malloc(strlen(duplicateArray) + 1);
    strcpy(result, duplicateArray);
    
    return result;
}

int main() {
    char str[] = "Bubble Occurrence Mammal cpro";
    
    char* result = removeNonDuplicate(str);
    
    printf("%s\n", result);
    
    free(result);
    
    return 0;
}



/*
run:

ubble ccurrece ammal cr

*/

 



answered Mar 20, 2024 by avibootz

Related questions

2 answers 183 views
1 answer 112 views
1 answer 130 views
1 answer 122 views
1 answer 123 views
1 answer 123 views
1 answer 103 views
...