Java的:排序在数字方式的String数组 [英] Java: Sort a String array in a numeric way
本文介绍了Java的:排序在数字方式的String数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含以下条目的String数组:
I have a String array that contains the following entries:
Array[0] = "70% Marc"
Array[1] = "50% Marc"
Array[2] = "100% Marc"
Array[3] = "20% Marc"
和我想排序数组下降。
当我使用 Arrays.sort(阵列)
那么它的排序,上去下来,但 100%马克
是在底部(因为它只着眼于第一个字符来排序的话)。我希望它进行排序是这样的:
And I would like to sort this array descending.
When I use Arrays.sort(Array)
then it does sort it descending but the 100% Marc
is at the bottom (because it only looks at the first character to sort it). I want it to be sorted like this:
"100% Marc"
"70% Marc"
"50% Marc"
"20% Marc"
我怎么能这样做?
How can I do that?
推荐答案
自己写的 CustomStringComparator
和排序方法使用它。
Write your own CustomStringComparator
and use it with the sort method.
public class CustomStringComparator implements Comparator<String>{
@Override
public int compare(String str1, String str2) {
// extract numeric portion out of the string and convert them to int
// and compare them, roughly something like this
int num1 = Integer.parseInt(str1.substring(0, str1.indexOf("%") - 1));
int num2 = Integer.parseInt(str2.substring(0, str2.indexOf("%") - 1));
return num1 - num2;
}
}
这篇关于Java的:排序在数字方式的String数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文