C++ string sort like a human being?

后端 未结 4 2068
灰色年华
灰色年华 2021-02-05 23:12

I would like to sort alphanumeric strings the way a human being would sort them. I.e., \"A2\" comes before \"A10\", and \"a\" certainly comes before \"Z\"! Is there any way to d

4条回答
  •  -上瘾入骨i
    2021-02-05 23:55

    It really depends what you mean by "parser." If you want to avoid writing a parser, I would think you should avail yourself of library functions.

    • Treat the string as a sequence of subsequences which are uniformly alphabetic, numeric, or "other."
    • Get the next alphanumeric sequence of each string using isalnum and backtrack-checking for + or - if it is a number. Use strtold in-place to find the end of a numeric subsequence.
    • If one is numeric and one is alphabetic, the string with the numeric subsequence comes first.
    • If one string has run out of characters, it comes first.
    • Use strcoll to compare alphabetic subsequences within the current locale.
    • Use strtold to compare numeric subsequences within the current locale.
    • Repeat until finished with one or both strings.
    • Break ties with strcmp.

    This algorithm has something of a weakness in comparing numeric strings which exceed the precision of long double.

提交回复
热议问题