How to sort number in alphanumeric

前端 未结 5 389
失恋的感觉
失恋的感觉 2021-01-03 01:16

Input:

SHC 111U,SHB 22x,, SHA 5555G

Needed output:

SHB 22X, SHC 111U, SHA 5555G

I

5条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-03 01:35

    There is nothing built-in to do this, but you can do it by first extracting the numbers and sorting based on that. For example:

    class VehicleNumberComparer : IComparer
    {
        public int Compare(string lhs, string rhs)
        {
            var numExtract = new Regex("[0-9]+");
            int lhsNumber = int.Parse(numExtract.Match(lhs).Value);
            int rhsNumber = int.Parse(numExtract.Match(rhs).Value);
            return lhsNumber.CompareTo(rhsNumber);
        }
    }
    

    This is untested (and probably won't even compile without modification), has no error checking, and probably isn't the fastest method in the world, but should give you an idea.

提交回复
热议问题