Remove Duplicates & Sort Characters in C
Here is a sample code that can remove duplicate characters and sort the characters:
#include <stdio.h>
#include <string.h>
void removeDuplicatesAndSort(char* str) {
int len = strlen(str);
int index = 0;
// Remove duplicates
for (int i = 0; i < len; i++) {
int j;
for (j = 0; j < index; j++) {
if (str[i] == str[j]) {
break;
}
}
if (j == index) {
str[index++] = str[i];
}
}
// Sort characters
for (int i = 0; i < index - 1; i++) {
for (int j = i + 1; j < index; j++) {
if (str[i] > str[j]) {
char temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
}
str[index] = '\0';
}
int main() {
char str[] = "hello";
// Remove duplicates and sort characters
removeDuplicatesAndSort(str);
printf("Result: %s\n", str);
return 0;
}
In the example code above, we first define a function called removeDuplicatesAndSort. This function takes a string as input, removes duplicate characters, and sorts the characters. Then we call this function in the main function and print the processed result. You can copy and paste the example code above into a C file, compile and run it to see the output result.