C言語 文字列の重複削除とソート処理【サンプルコード付き】
以下は、重複する文字を削除し、文字をソートするサンプルコードです。
#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;
}
上記のコード例では、まずremoveDuplicatesAndSortという関数を定義し、文字列を受け取り重複した文字を削除し、文字をソートします。その後、main関数でこの関数を呼び出し、処理結果をプリントします。上記のコード例をCファイルにコピー&ペーストしてコンパイル実行して、出力結果を確認してみてください。