方法1:直接用数组排序
public class StringSort {
public static void main(String[] args) {
String[] strings = {"abc123", "abc+1234", "ababab--1"};
// 对每个字符串计算字母字符个数和数字字符个数,并按照字母数字比和字符串本身大小排序
Arrays.sort(strings, (s1, s2) -> {
int alphaCount1 = 0, numericCount1 = 0;
for (char c : s1.toCharArray()) {
if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') alphaCount1++;
else if (c >= '0' && c <= '9') numericCount1++;
}
double ratio1 = numericCount1 == 0 ? Double.MAX_VALUE : (double) alphaCount1 / numericCount1;
int alphaCount2 = 0, numericCount2 = 0;
for (char c : s2.toCharArray()) {
if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') alphaCount2++;
else if (c >= '0' && c <= '9') numericCount2++;
}
double ratio2 = numericCount2 == 0 ? Double.MAX_VALUE : (double) alphaCount2 / numericCount2;
if (ratio1 < ratio2) return 1;
else if (ratio1 > ratio2) return -1;
else return s2.compareTo(s1); // 按照降序排列
});
// 输出排序后的结果
System.out.println(Arrays.toString(strings));
}
}