How to use compare on a version number where theres less parts in one number in Objective-C?

前端 未结 9 603
感情败类
感情败类 2021-01-22 02:30

I\'ve found the following code at http://snipplr.com/view/2771

Which is pretty good, almost exactly what I was looking for, but if I use the values @\"1.4.5\", @

9条回答
  •  执念已碎
    2021-01-22 02:49

    My sense would be that the first numeral group is always the most significant, so 10.anything is bigger than 9.anything.anything. If I'm right about that, then the solution is to replace the dots with zeros and pad the shorter string on the right-hand side with zeros to match the length of the longer string:

    e.g.
    9.4   --->  90400  (padded on the right with 00)
    8.6.7 --->  80607
    

    What's nice about this is, that if I'm wrong about the requirement, the algorithm can be readily fixed by padding the shorter string on the right.

    - (NSComparisonResult)compareVersion:(NSString *)vA withVersion:(NSString *)vB {
    
        NSString *vAPadded = [vA stringByReplacingOccurrencesOfString:@"." withString:@"0"];
        NSString *vBPadded = [vB stringByReplacingOccurrencesOfString:@"." withString:@"0"];
    
        while (vAPadded.length < vBPadded.length)
            vAPadded = [vAPadded stringByAppendingString:@"0"];
    
        while (vBPadded.length < vAPadded.length)
            vBPadded = [vBPadded stringByAppendingString:@"0"];
    
        return [vAPadded intValue] - [vBPadded intValue];
    }
    

    If I've got the requirement backwards on significant digits, change the pads like this:

    vAPadded = [@"0" stringByAppendingString:vAPadded];
    

提交回复
热议问题