Sort on a string that may contain a number

前端 未结 23 2306
走了就别回头了
走了就别回头了 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:38

    Although the question asked a java solution, for anyone who wants a scala solution:

    object Alphanum {
    
       private[this] val regex = "((?<=[0-9])(?=[^0-9]))|((?<=[^0-9])(?=[0-9]))"
    
       private[this] val alphaNum: Ordering[String] = Ordering.fromLessThan((ss1: String, ss2: String) => (ss1, ss2) match {
         case (sss1, sss2) if sss1.matches("[0-9]+") && sss2.matches("[0-9]+") => sss1.toLong < sss2.toLong
         case (sss1, sss2) => sss1 < sss2
       })
    
       def ordering: Ordering[String] = Ordering.fromLessThan((s1: String, s2: String) => {
         import Ordering.Implicits.infixOrderingOps
         implicit val ord: Ordering[List[String]] = Ordering.Implicits.seqDerivedOrdering(alphaNum)
    
         s1.split(regex).toList < s2.split(regex).toList
       })
    
    }
    

提交回复
热议问题