2016-05-29 154 views
0

如何才能打印下列數組中的每種顏色? 我在尋找的輸出是一樣的東西 RED BLUE 白色 ...打印字符串數組的部分

char *my_array[20]={"RED","BLUE","WHITE","BLUE","YELLOW","BLUE","RED","YELLOW","WHITE","BLUE","BLACK","BLACK","WHITE","RED","YELLOW","BLACK","WHITE","BLUE","RED","YELLOW"}; 
+1

使用:'const char *'來防止意外修改未定義行爲的文字。 –

+0

創建一個指向'my_array'中唯一值的指針數組並打印這些指針。 –

+0

事實上,我正在尋找的答案是在其他帖子....對不起,重複... –

回答

0

如果你對它們進行排序,那麼你可以查看最後重複的元素是否是前一個元素,並打印出來,否則保持這樣搜索

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

int 
compare(const void *const str1, const void *const str2) 
{ 
    return strcmp(str1, str2); 
} 

int 
main(void) 
{ 
    const char *my_array[20] = { 
     "RED", "BLUE", "WHITE", "BLUE", "YELLOW", "BLUE", "RED", 
     "YELLOW", "WHITE", "BLUE", "BLACK", "BLACK", "WHITE", 
     "RED", "YELLOW", "BLACK", "WHITE", "BLUE", "RED", 
     "YELLOW" 
    }; 
    const char *last; 
    size_t count; 

    count = sizeof(my_array)/sizeof(*my_array); 
    if (count == 0) // What? 
     return -1; 
    qsort(my_array, count, sizeof(*my_array), compare); 

    last = my_array[0]; 
    for (size_t i = 1 ; i < count ; ++i) 
    { 
     if (strcmp(last, my_array[i]) == 0) 
      continue; 
     fprintf(stdout, "%s\n", last); 
     last = my_array[i]; 
    } 
    // The last one 
    fprintf(stdout, "%s\n", last); 
    return 0; 
}