0

I am writing a code in which I have to sort an array by ASCII, change upper letters to lower letters and also words which begin with "ch" have to be placed after words which begin with "h". This is my code:


int scp(const char *str1, const char *str2) {
    const unsigned char *c1 = (const unsigned char *)str1,
    *c2 = (const unsigned char *)str2;
    while (*c1 && *c2){
        if (toupper(*c1) != toupper(*c2))
            return toupper(*c1) - toupper(*c2);
        c1++; c2++;
    }
    return 0;
}


int comWor(const void *x, const void *y) {
    const char *fir = *(const char **) x;
    const char *sec = *(const char **) y;
    return scp(fir, sec);
}


void sortArray(char **listOfW, int count) {
    qsort(listOfW, count, sizeof(char *), comWor);
}


The code works for sorting an array by ASCII and also changes upper letters to lower letters, but I do not know what to do about that "words which begin with "ch" have to be placed after words which begin with "h"" part. Any ideas, please?

dfps12
  • 75
  • 5
  • 1
    Did you consider changing `scp()` so that it, first, makes the comparison where it checks that one of the words starts with "ch", the other one with "h", and returns the appropriate return value, accordingly, before doing what it does now, in all other situations? – Sam Varshavchik Dec 29 '19 at 00:16
  • a word that begins with "ch" also begins with "c", so they will always be behind words which begins with "h". Do you mean that "ch" words should be placed *after* "h" words? – prmottajr Dec 29 '19 at 00:17
  • 3
    Are you using C or C++? The code looks like C. For C++ you should be using a `std::vector` for you list of words and then us [this](https://stackoverflow.com/questions/313970/how-to-convert-stdstring-to-lower-case) to make it lower case and the [this](https://stackoverflow.com/questions/3418231/replace-part-of-a-string-with-another-string) – NathanOliver Dec 29 '19 at 00:19
  • to change the characters. – NathanOliver Dec 29 '19 at 00:19
  • @prmottajr Yes, words which begin with "ch" have to be placed after words which begin with "h". – dfps12 Dec 29 '19 at 00:26
  • To place words which being with "ch" after those that being with "h", sort again, but use a comparator that - unlike your current one - deems a word starting with "ch" is greater than those that start with "h". Also, this is C++ - the `std::sort()` algorithm is at least as effective than `qsort()`, and offers greater type safety. – Peter Dec 29 '19 at 07:11

0 Answers0