打印字符串数组的部分

时间:2016-05-29 14:43:22

标签: c arrays string printf

我如何才能打印下列数组中的每种颜色? 我想要的输出是这样的 红色 蓝色 白色 ...

{{1}}

1 个答案:

答案 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;
}