Sort on a string that may contain a number

前端 未结 23 2320
走了就别回头了
走了就别回头了 2020-11-22 02:59

I need to write a Java Comparator class that compares Strings, however with one twist. If the two strings it is comparing are the same at the beginning and end of the strin

23条回答
  •  滥情空心
    2020-11-22 03:26

    Prior to discovering this thread, I implemented a similar solution in javascript. Perhaps my strategy will find you well, despite different syntax. Similar to above, I parse the two strings being compared, and split them both into arrays, dividing the strings at continuous numbers.

    ...
    var regex = /(\d+)/g,
        str1Components = str1.split(regex),
        str2Components = str2.split(regex),
    ...
    

    I.e., 'hello22goodbye 33' => ['hello', 22, 'goodbye ', 33]; Thus, you can walk through the arrays' elements in pairs between string1 and string2, do some type coercion (such as, is this element really a number?), and compare as you walk.

    Working example here: http://jsfiddle.net/F46s6/3/

    Note, I currently only support integer types, though handling decimal values wouldn't be too hard of a modification.

提交回复
热议问题