Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <pre><code>#include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; #include &lt;string.h&gt; typedef struct { unsigned char message[100]; // string to be sorted // (totally arbitrary length) unsigned char sortOrder[256]; // string containing ASCII chars // in their sort order } Pair; unsigned char rank[256]; // rank of each ASCII character // qsort() comparison function int sortByRank(const void *a, const void *b) { return ((int)rank[*(signed char *)a] - (int)rank[*(signed char *)b]); } // Creates an array by which a character's relative position can be found // solely from its value. Characters of rank 0 will appear first when sorted. // Characters not specified by sortOrder will appear first, since rank is // global and automatically initialized to zeros. void initRank(Pair pair) { int i; for (i = 0; i &lt; strlen(pair.sortOrder); i++) rank[pair.sortOrder[i]] = i; return; } int main() { // Create an example pair. Spaces will be the first characters in the // sorted result. Pair pair; strcpy(pair.message, "this is a test message (123)."); strcpy(pair.sortOrder, " 321abcdefghijklm.nopqrstuvwxyz()"); // In this solution, initRank() will need to be called any time the // sortOrder is changed. initRank(pair); // Sort using the global rank array set by initRank() qsort(pair.message, strlen(pair.message), sizeof(char), sortByRank); printf("Sorted message: %s\n", pair.message); // Output: // Sorted message: 321aaeeeghiim.sssssttt() return 0; } </code></pre> <p>Since rank[] is global, this isn't as elegant as might be, but the above solution generally demonstrates how to make use of C's sorting function to do a custom sort based on a second string in a fairly straightforward manner.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload