Java:以数字方式对字符串数组进行排序 [英] Java: Sort a String array in a numeric way
本文介绍了Java:以数字方式对字符串数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含以下条目的字符串数组:
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(Array)
然后它会降序排序但 100% Marc
在底部(因为它只查看第一个字符来对其进行排序).我希望它像这样排序:
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"
我该怎么做?
推荐答案
编写自己的 CustomStringComparator
并与 sort 方法一起使用.
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:以数字方式对字符串数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文