api列表

  1. compareVersion :版本号比较,0代表相等,1代表version1大于version2,-1代表version1小于version2

源码

  1. object StringUtils {
  2. /**
  3. * 版本号比较,0代表相等,1代表version1大于version2,-1代表version1小于version2
  4. *
  5. * @param version1
  6. * @param version2
  7. * @return
  8. */
  9. fun compareVersion(version1: String, version2: String): Int {
  10. if (version1 == version2) {
  11. return 0
  12. }
  13. val version1Array = version1.split("\\.".toRegex()).toTypedArray()
  14. val version2Array = version2.split("\\.".toRegex()).toTypedArray()
  15. var index = 0
  16. // 获取最小长度值
  17. val minLen = Math.min(version1Array.size, version2Array.size)
  18. var diff = 0
  19. // 循环判断每位的大小
  20. while (index < minLen
  21. && version1Array[index].toInt() - version2Array[index].toInt().also { diff = it } == 0
  22. ) {
  23. index++
  24. }
  25. return if (diff == 0) {
  26. // 如果位数不一致,比较多余位数
  27. for (i in index until version1Array.size) {
  28. if (version1Array[i].toInt() > 0) {
  29. return 1
  30. }
  31. }
  32. for (i in index until version2Array.size) {
  33. if (version2Array[i].toInt() > 0) {
  34. return -1
  35. }
  36. }
  37. 0
  38. } else {
  39. if (diff > 0) 1 else -1
  40. }
  41. }
  42. }