gpt4 book ai didi

java - 字符串版本比较

转载 作者:太空宇宙 更新时间:2023-11-04 15:08:02 26 4
gpt4 key购买 nike

嗨,我有字符串数组

String version[] = {"3.1.2","2.1.7","3.1.1","3.7.3","2.6.4","1.3.4.7"};

我想在其中找到最新版本。哪种方法会好呢?它应该打印 3.7.3

最佳答案

这是一个使用比较器的示例

public static void main(String[] args) {
String version[] = { "3.1.2", "2.1.7", "3.1222.1", "3.10.1", "3.10",
"3.7.3", "2.6.4", "1.3.4.7" };
Arrays.sort(version, new Comparator<String>() {

@Override
public int compare(String o1, String o2) {
//Split tokens into arrays
String[] tokens1 = o1.split("\\.");
String[] tokens2 = o2.split("\\.");

//Compare existing elements of each array
for (int i = 0; i < tokens1.length && i < tokens2.length; i++) {
int comparison = Integer.valueOf(tokens1[i]).compareTo(
Integer.valueOf(tokens2[i]));
if (comparison != 0) {
return comparison;
}
}
//Compare how specific each version is promote the most general
//Only considered if version lengths != in size but equal in compared tokens
return tokens1.length - tokens2.length;
}

});

for (String v : version) {
System.out.println(v);
}
}

关于java - 字符串版本比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21724419/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com