文字列をソート・ユニークする関数を実装
第一引数のstrの文字列をソート・ユニークして、第二引数のoutStrに入力する
void sortUniqStr(char* str, char* outStr){
int hash[SIZE] = {0};
int i,j;
int len = strlen(str);
for(i = 0; i < len ; i++){
hash[ str[i] ]++;
}
for(i = 0, j = 0; i < SIZE ; i++){
if(hash[i] != 0){
outStr[j] = i;
j++;
}
}
outStr[j] = '\0';
return;
}
ハッシュを使って、出現してきた文字列をカウントします。
for(i = 0; i < len ; i++){
hash[ str[i] ]++;
}
その後、先頭の文字から、カウントが1以上の文字列を出力していきます。
最後に、NULL文字を入れるのを忘れないことが大事です。
for(i = 0, j = 0; i < SIZE ; i++){
if(hash[i] != 0){
outStr[j] = i;
j++;
}
}
outStr[j] = '\0';
サンプルコード
下記がサンプルコードになります。
$ cat sample.c
#include <stdio.h>
#include <string.h>
#define SIZE 256
void sortUniqStr(char* str, char* outStr){
int hash[SIZE] = {0};
int i,j;
int len = strlen(str);
for(i = 0; i < len ; i++){
hash[ str[i] ]++;
}
for(i = 0, j = 0; i < SIZE ; i++){
if(hash[i] != 0){
outStr[j] = i;
j++;
}
}
outStr[j] = '\0';
return;
}
int main(){
char* str = "abbcdeac";
char outStr[SIZE] = {0};
sortUniqStr(str, outStr);
printf("%s", outStr);
return 0;
}
下記が実行結果になります。
$ gcc -o sample sample.c $ ./sample abcde
