How to sort Alphanumeric String

前端 未结 11 1429
我寻月下人不归
我寻月下人不归 2020-12-10 06:25

I have a problem with sorting strings which include integers. If I use the below code I get sorting like: 1some, 2some, 20some, 21some, 3some, some

However I want it

11条回答
  •  执笔经年
    2020-12-10 07:04

    You need to implement your own Comparator to do this kind of custom sorting. The default String.compareTo() method seems to sort numbers before characters. When 0 in 20some gets compared to s in 3some the 0 has a higher sort priority and therefore the whole word gets sorted in first.
    What you would need to do is this: try to split you strings into the number and the character part. That's a hard task since those Strings can consist of many of those parts (or don't they?). You may use algorithms like Alphanum, which Murtaza already showed to you.
    If you want to implement it yourself, you could check, where the number part ends. Then parse it to an int with Integer.parse(). Compare int parts if they exist in both Strings, then compare the rest. Well that may not be the most professional solution, but as a beginner you may want craft those things yourself to learn it.

提交回复
热议问题