是否有比较版本号的标准习语?我不能直接使用String compareTo,因为我还不知道点释放的最大数量是多少。我需要比较版本,并有以下保持正确:
1.0 < 1.1
1.0.1 < 1.1
1.9 < 1.10
是否有比较版本号的标准习语?我不能直接使用String compareTo,因为我还不知道点释放的最大数量是多少。我需要比较版本,并有以下保持正确:
1.0 < 1.1
1.0.1 < 1.1
1.9 < 1.10
当前回答
@alex在Kotlin上的帖子
class Version(inputVersion: String) : Comparable<Version> {
var version: String
private set
override fun compareTo(other: Version) =
(split() to other.split()).let {(thisParts, thatParts)->
val length = max(thisParts.size, thatParts.size)
for (i in 0 until length) {
val thisPart = if (i < thisParts.size) thisParts[i].toInt() else 0
val thatPart = if (i < thatParts.size) thatParts[i].toInt() else 0
if (thisPart < thatPart) return -1
if (thisPart > thatPart) return 1
}
0
}
init {
require(inputVersion.matches("[0-9]+(\\.[0-9]+)*".toRegex())) { "Invalid version format" }
version = inputVersion
}
}
fun Version.split() = version.split(".").toTypedArray()
用法:
Version("1.2.4").compareTo(Version("0.0.5")) //return 1
其他回答
我喜欢@Peter Lawrey的想法,我把它扩展到更远的范围:
/**
* Normalize string array,
* Appends zeros if string from the array
* has length smaller than the maxLen.
**/
private String normalize(String[] split, int maxLen){
StringBuilder sb = new StringBuilder("");
for(String s : split) {
for(int i = 0; i<maxLen-s.length(); i++) sb.append('0');
sb.append(s);
}
return sb.toString();
}
/**
* Removes trailing zeros of the form '.00.0...00'
* (and does not remove zeros from, say, '4.1.100')
**/
public String removeTrailingZeros(String s){
int i = s.length()-1;
int k = s.length()-1;
while(i >= 0 && (s.charAt(i) == '.' || s.charAt(i) == '0')){
if(s.charAt(i) == '.') k = i-1;
i--;
}
return s.substring(0,k+1);
}
/**
* Compares two versions(works for alphabets too),
* Returns 1 if v1 > v2, returns 0 if v1 == v2,
* and returns -1 if v1 < v2.
**/
public int compareVersion(String v1, String v2) {
// Uncomment below two lines if for you, say, 4.1.0 is equal to 4.1
// v1 = removeTrailingZeros(v1);
// v2 = removeTrailingZeros(v2);
String[] splitv1 = v1.split("\\.");
String[] splitv2 = v2.split("\\.");
int maxLen = 0;
for(String str : splitv1) maxLen = Math.max(maxLen, str.length());
for(String str : splitv2) maxLen = Math.max(maxLen, str.length());
int cmp = normalize(splitv1, maxLen).compareTo(normalize(splitv2, maxLen));
return cmp > 0 ? 1 : (cmp < 0 ? -1 : 0);
}
希望它能帮助到别人。它通过了interviewbit和leetcode中的所有测试用例(需要取消compareVersion函数中的两行注释)。
很容易测试!
基于https://stackoverflow.com/a/27891752/2642478
class Version(private val value: String) : Comparable<Version> {
private val splitted by lazy { value.split("-").first().split(".").map { it.toIntOrNull() ?: 0 } }
override fun compareTo(other: Version): Int {
for (i in 0 until maxOf(splitted.size, other.splitted.size)) {
val compare = splitted.getOrElse(i) { 0 }.compareTo(other.splitted.getOrElse(i) { 0 })
if (compare != 0)
return compare
}
return 0
}
}
你可以用like:
System.err.println(Version("1.0").compareTo( Version("1.0")))
System.err.println(Version("1.0") < Version("1.1"))
System.err.println(Version("1.10") > Version("1.9"))
System.err.println(Version("1.10.1") > Version("1.10"))
System.err.println(Version("0.0.1") < Version("1"))
public static int compareVersions(String version1, String version2){
String[] levels1 = version1.split("\\.");
String[] levels2 = version2.split("\\.");
int length = Math.max(levels1.length, levels2.length);
for (int i = 0; i < length; i++){
Integer v1 = i < levels1.length ? Integer.parseInt(levels1[i]) : 0;
Integer v2 = i < levels2.length ? Integer.parseInt(levels2[i]) : 0;
int compare = v1.compareTo(v2);
if (compare != 0){
return compare;
}
}
return 0;
}
使用Maven真的很简单:
import org.apache.maven.artifact.versioning.DefaultArtifactVersion;
DefaultArtifactVersion minVersion = new DefaultArtifactVersion("1.0.1");
DefaultArtifactVersion maxVersion = new DefaultArtifactVersion("1.10");
DefaultArtifactVersion version = new DefaultArtifactVersion("1.11");
if (version.compareTo(minVersion) < 0 || version.compareTo(maxVersion) > 0) {
System.out.println("Sorry, your version is unsupported");
}
您可以从这个页面获得Maven Artifact的正确依赖项字符串:
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-artifact</artifactId>
<version>3.0.3</version>
</dependency>
由于本页上没有答案能很好地处理混合文本,我做了自己的版本:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Main {
static double parseVersion(String v) {
if (v.isEmpty()) {
return 0;
}
Pattern p = Pattern.compile("^(\\D*)(\\d*)(\\D*)$");
Matcher m = p.matcher(v);
m.find();
if (m.group(2).isEmpty()) {
// v1.0.0.[preview]
return -1;
}
double i = Integer.parseInt(m.group(2));
if (!m.group(3).isEmpty()) {
// v1.0.[0b]
i -= 0.1;
}
return i;
}
public static int versionCompare(String str1, String str2) {
String[] v1 = str1.split("\\.");
String[] v2 = str2.split("\\.");
int i = 0;
for (; i < v1.length && i < v2.length; i++) {
double iv1 = parseVersion(v1[i]);
double iv2 = parseVersion(v2[i]);
if (iv1 != iv2) {
return iv1 - iv2 < 0 ? -1 : 1;
}
}
if (i < v1.length) {
// "1.0.1", "1.0"
double iv1 = parseVersion(v1[i]);
return iv1 < 0 ? -1 : (int) Math.ceil(iv1);
}
if (i < v2.length) {
double iv2 = parseVersion(v2[i]);
return -iv2 < 0 ? -1 : (int) Math.ceil(iv2);
}
return 0;
}
public static void main(String[] args) {
System.out.println("versionCompare(v1.0.0, 1.0.0)");
System.out.println(versionCompare("v1.0.0", "1.0.0")); // 0
System.out.println("versionCompare(v1.0.0b, 1.0.0)");
System.out.println(versionCompare("v1.0.0b", "1.0.0")); // -1
System.out.println("versionCompare(v1.0.0.preview, 1.0.0)");
System.out.println(versionCompare("v1.0.0.preview", "1.0.0")); // -1
System.out.println("versionCompare(v1.0, 1.0.0)");
System.out.println(versionCompare("v1.0", "1.0.0")); // 0
System.out.println("versionCompare(ver1.0, 1.0.1)");
System.out.println(versionCompare("ver1.0", "1.0.1")); // -1
}
}
不过,在需要比较“alpha”和“beta”的情况下,它仍然不够。