2016-05-29 153 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; 
}