c - 在 C 中使用 qsort() 并跳过特定的字符集

标签 c qsort

#define alen(x) ((sizeof x) / (sizeof *x))

typedef struct {
    char *movie_title;
    int minutes;
    float price;
} DVD;

int
main()
{
    DVD movies[10] = {
        { "The Dark Knight", 153, 14.99},
        { "Iron Man", 126, 12.99},
        { "Batman Begins", 141, 9.99},
        { "Batman Returns", 126, 9.99},
        { "Teenage Mutant Ninja Turtles", 87, 7.99},
        { "The Incredible Hulk", 114, 12.99},
        { "X-Men", 104, 12.99},
        { "Spider-Man", 121, 14.99},
        { "Fantastic Four", 106, 14.99},
        { "Captain America", 124, 19.99},
    };

    qsort(movies, alen(movies), sizeof *movies, tcomp);

    printf("Movies sorted: \n");
    for (int i = 0; i < alen(movies); i++)
        printf("%s\n", movies[i].movie_title);
}

int
tcomp (const void * a, const void * b)
{
    return strcmp(((DVD*)a)->movie_title,((DVD*)b)->movie_title);
}

当使用函数 tcomp 和 qsort 对电影片名进行排序时,我需要忘记电影片名中的“A”、“An”和“The”。有人可以帮我弄清楚如何以优雅的方式做到这一点吗?

最佳答案

如果你只关心前缀词,那么在你做比较之前,调整指针

char* skip_irrelvant(char* s)
{
   while(*s == ' ') s++;
   if(strnicmp(s, "The ", 4)==0) s+=4;
   return s;
}


    int tcomp (const void * a, const void * b)
    {
       char* s1 = ((DVD*)a)->movie_title;
       char* s2 = ((DVD*)b)->movie_title;
       s1 = skip_irrelvant(s1);
       s2 = skip_irrelvant(s2);

       return strcmp(s1, s2);
    }

关于c - 在 C 中使用 qsort() 并跳过特定的字符集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10907358/

相关文章:

c - C 中的可变大小数组

c - qsort 在 c 中按字典顺序对字符串进行排序

c - 在 C 中按长度对字符串进行排序

c - for循环中的数组未获得正确的值

c - 如何安全地将两个可变大小的数据类型(结构)放在一个结构中?

c - 为什么“while(!feof(file))”总是错误的?

c++ - 如何使用 qsort 对结构(由几个不同的元素组成)进行排序?

python - 使用 Cython 作为 Python 到 C 的转换器

c - 有没有类似qsort()的函数可以用在内核空间?

c - 按 2 个参数对结构体数组进行排序