Natural sort in C - “array of strings, containing numbers and letters”

后端 未结 4 816
被撕碎了的回忆
被撕碎了的回忆 2021-01-24 06:34

Looking for a proven to work algorithm for production. Did see this example but not finding much else on the web or in books.

i.e. file_10.txt > file_2.txt

Thank

4条回答
  •  情歌与酒
    2021-01-24 07:31

    I assume you already know the C standard library qsort() function:

    void qsort(void *base,
               size_t nel,
               size_t width,
               int (*compar)(const void *, const void *);
    

    That last parameter is a function pointer, which means you can pass any function to it. You could use strcmp(), in fact, but that would give you ASCIIbetical, and you specifically want a natural sort.

    In that case, you could write one pretty easily:

    #include 
    
    int natural(const char *a, const char *b)
    {
        if(isalpha(*a) && isalpha(*b))
          {
            // compare two letters
          }
        else
          {
            if(isalpha(*a))
              {
                // compare a letter to a digit (or other non-letter)
              }
            else if(isalpha(*b))
              {
                // compare a digit/non-letter to a letter
              }
            else
              {
                // compare two digits/non-letters
              }
          }
    }
    

    Some of the elses could be cleared up if you just return early, but there's a basic structure. Check ctype.h for functions like isalpha() (if a character is part of the alphabet), isdigit(), isspace(), and more.

提交回复
热议问题