0
#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”。有人可以帮我弄清楚如何以优雅的方式做到这一点吗?

4

2 回答 2

3

如果您只关心前缀词,那么在进行比较之前,请调整指针

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);
    }
于 2012-06-06T02:20:08.843 回答
0

编写一个函数来在比较之前从名称的临时副本中删除您想要的忽略单词?

然后简单地比较处理后的名称。

我想这应该很简单,可以通过空格分隔来实现这样的功能,然后在将单词推入输出字符串之前确保单词是“有效单词”。

于 2012-06-06T02:20:10.177 回答