Question:

C Programming - ignore case sorting (Part 2)?

by  |  earlier

0 LIKES UnLike

Hi everybody,

So my previous question involved turning 2D arrays into lower case form. This is because I am trying to write a sorting function involving qsort which does several things. These things involve sorting strings in reverse order, ignoring case, and ignoring leading spaces.

I've manage to get the reverse order working simply by passing a negative value through the fourth parameter of qsort. I am still a bit confused as to what to do in the event of when the ignore case option is turned on. This is what I have:

void sort(char *string[], size_t strings_len, int reverseFlag, int caseFlag, int wSpaceFlag)

{

if(reverseFlag == 0){

printf("\n***ASCENDING***\n");

if(caseFlag == 1){

/* unsure of what to put here */

}

else{

qsort(string, strings_len, sizeof(char *), aCmp);

print(string, strings_len);

}

}

if(reverseFlag == 1){

printf("\n***DESCENDING***\n");

qsort(string, strings_len, sizeof(char *), dCmp);

print(string, strings_len);

}

}

The print() function after the qsort function is customized. *string[] basically contains the string "BOY apple cow" where *string would point to "BOY". If the ignore case flag isn't turned on, the output would generate:

BOY

apple

cow

(in ascending order).

Although, i'm trying to make it so that when it ignores cases, the output would be:

apple

BOY

cow

(still in ascending order).

Can anyone provide me tips on where to start?

Help is greatly appreciated.

Thanks.

 Tags:

   Report

1 ANSWERS


  1. If ignoring case, you'll need to convert all characters to the same case, lower or upper. You should make a copy of the input string array, sort that, then copy it back to the input string array.

    The code may look something like this:

    /* copy string[ ] to string_copy[ ] */

    if (caseFlag == 1) {

      int i;  

      char *p;

      for (i = 0; i < strings_len; i++) {

        p = string_copy[i];

        while (*p != '\0') {

          *p = tolower(*p);

           p++;

        }

      }

    }

    /* sort string_copy[ ] */

    /* copy string_copy[ ] to string[ ] */

    EDIT: another option, maybe not as good, would be to add 2 more comparison functions, for ascending and descending, case ignoring compare.

Question Stats

Latest activity: earlier.
This question has 1 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.