比较两个版本字符串

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了比较两个版本字符串相关的知识,希望对你有一定的参考价值。

  1. /*
  2.  * compareVersions(@"10.4", @"10.3") returns NSOrderedDescending (1)
  3.  * compareVersions(@"10.5", @"10.5.0") returns NSOrderedSame (0)
  4.  * compareVersions(@"10.4 Build 8L127", @"10.4 Build 8P135") returns NSOrderedAscending (-1)
  5.  */
  6. NSComparisonResult compareVersions(NSString* leftVersion, NSString* rightVersion)
  7. {
  8. int i;
  9.  
  10. // Break version into fields (separated by '.')
  11. NSMutableArray *leftFields = [[NSMutableArray alloc] initWithArray:[leftVersion componentsSeparatedByString:@"."]];
  12. NSMutableArray *rightFields = [[NSMutableArray alloc] initWithArray:[rightVersion componentsSeparatedByString:@"."]];
  13.  
  14. // Implict ".0" in case version doesn't have the same number of '.'
  15. if ([leftFields count] < [rightFields count]) {
  16. while ([leftFields count] != [rightFields count]) {
  17. [leftFields addObject:@"0"];
  18. }
  19. } else if ([leftFields count] > [rightFields count]) {
  20. while ([leftFields count] != [rightFields count]) {
  21. [rightFields addObject:@"0"];
  22. }
  23. }
  24.  
  25. // Do a numeric comparison on each field
  26. for(i = 0; i < [leftFields count]; i++) {
  27. NSComparisonResult result = [[leftFields objectAtIndex:i] compare:[rightFields objectAtIndex:i] options:NSNumericSearch];
  28. if (result != NSOrderedSame) {
  29. [leftFields release];
  30. [rightFields release];
  31. return result;
  32. }
  33. }
  34.  
  35. [leftFields release];
  36. [rightFields release];
  37. return NSOrderedSame;
  38. }

以上是关于比较两个版本字符串的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Bash 中比较两个点分隔版本格式的字符串?

字符串165. 比较版本号

js 比较两个版本的大小 比如 4.5.1和 4.6.2

比较版本号字符串

leetcode165. 比较版本号

165 Compare Version Numbers 比较版本号