import java.util.Comparator;
/**
* 字符串混合排序
*/
public class StringComparator implements Comparator<String> {
@Override
public int compare(String o1, String o2) {
if (o1.equals(o2)) {
return 0;
}
int i = 0, j = 0;
String temp1, temp2;
int sum1, sum2;
int len1 = o1.length();
int len2 = o2.length();
int length = Math.min(len1, len2);
while (i < length && j < length) {
temp1 = "";
temp2 = "";
// 1、当前位置不是数字,要么区分大小,要么相等循环继续
if (o1.charAt(i) > '9' || o1.charAt(i) < '0' || o2.charAt(j) > '9'
|| o2.charAt(j) < '0') {
if (o1.charAt(i) == o2.charAt(j)) {
i++;
j++;
continue;
} else if (o1.charAt(i) > o2.charAt(j)) {
return 1;
} else {
return -1;
}
}
// 2、当前位置是数字,继续取后几位的数字,拼成字符串
while (i < len1 && o1.charAt(i) <= '9' && o1.charAt(i) >= '0') {
temp1 += o1.charAt(i);
i++;
}
while (j < len2 && o2.charAt(j) <= '9' && o2.charAt(j) >= '0') {
temp2 += o2.charAt(j);
j++;
}
// 计算字符串中数字的数值
sum1 = calculate(temp1);
sum2 = calculate(temp2);
// 如果数值相等,要么长度一致,那么i==j,循环继续;
// 要么长度不一致,长度较长的字符串前面是0,以0开头的放前面
if (sum1 == sum2) {
if (temp1.length() < temp2.length()) {
return 1;
} else if (temp1.length() > temp2.length()) {
return -1;
} else {
continue;
}
} else if (sum1 > sum2) {
return 1;
} else {
return -1;
}
}
// 超过较小长度,未判断出谁大谁小,即较长者放后面
return len1 > len2 ? 1 : -1;
}
/**
* 计算字符串数字的数值
*
* @param str
* @return
*/
private int calculate(String str) {
// 这里要小心,需要判断有效性
if (str == null || str.length() == 0) {
return 0;
}
int len = str.length();
double sum = 0;
int sign = 1;
int j = 0;
// 剔除字符串前方的空格
while (str.charAt(j) == ' ') {
j++;
}
// 判断正数和负数
if (str.charAt(j) == '+') {
sign = 1;
j++;
} else if (str.charAt(j) == '-') {
sign = -1;
j++;
}
// 计算剩余字符串
for (int i = j; i < len; i++) {
char current = str.charAt(i);
if (current >= '0' && current <= '9') {
sum = sum * 10 + (int) (current - '0');
} else {
// 碰到非数字,退出转换
break;
}
}
sum = sum * sign;
// 这里要小心,需要判断范围
if (sum > Integer.MAX_VALUE) {
sum = Integer.MAX_VALUE;
} else if (sum < Integer.MIN_VALUE) {
sum = Integer.MIN_VALUE;
}
return (int) sum;
}
}