This question already has answers here:
Finding unique elements in an string array in C
                                
                                    (5个答案)
                                
                        
                                3年前关闭。
            
                    
如何将以下阵列中的每种颜色仅打印一次?
我正在寻找的输出是这样的
红色
蓝色
白色
...

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

最佳答案

如果对它们排序,则可以检查最后一个重复的元素是否是前一个元素并打印出来,否则继续这样搜索

#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;
}

关于c - 打印一部分字符串数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37511230/

10-12 00:33
查看更多