C++ string sort like a human being?

后端 未结 4 2074
灰色年华
灰色年华 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

    Is there any way to do it without writing a mini parser? I would think the answer is no. But writing a parser isn't that tough. I had to do this a while ago to sort our company's stock numbers. Basically just scan the number and turn it into an array. Check the "type" of every character: alpha, number, maybe you have others you need to deal with special. Like I had to treat hyphens special because we wanted A-B-C to sort before AB-A. Then start peeling off characters. As long as they are the same type as the first character, they go into the same bucket. Once the type changes, you start putting them in a different bucket. Then you also need a compare function that compares bucket-by-bucket. When both buckets are alpha, you just do a normal alpha compare. When both are digits, convert both to integer and do an integer compare, or pad the shorter to the length of the longer or something equivalent. When they're different types, you'll need a rule for how those compare, like does A-A come before or after A-1 ?

    It's not a trivial job and you have to come up with rules for all the odd cases that may arise, but I would think you could get it together in a few hours of work.

提交回复
热议问题