Using qsort() in C and skipping specific sets of character -
#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"); (int = 0; < 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); } when sorting movie titles function tcomp , qsort need forgot "a", "an", , "the" in movie titles. can me figure out how in elegant manner?
if concerned prefix words, before compare, adjust pointers
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); }
Comments
Post a Comment