java实现中文数字的排序
时间: 2023-03-19 08:21:54 浏览: 89
要实现中文数字的排序,可以使用Java的Comparator接口来自定义排序规则。以下是一个实现中文数字排序的示例代码:
```java
import java.util.Comparator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ChineseNumberComparator implements Comparator<String> {
private static final String CHINESE_NUMBER_PATTERN = "[零一二三四五六七八九十百千万亿]+";
private static final String[] CHINESE_NUMBER_UNIT = new String[]{"亿", "万", "千", "百", "十"};
private static final int[] CHINESE_NUMBER_UNIT_VALUE = new int[]{100000000, 10000, 1000, 100, 10};
private static final String[] CHINESE_NUMBER_CHAR = new String[]{"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"};
private static int getChineseNumberValue(String s) {
int value = 0;
int lastUnit = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '零') {
continue;
}
int digit = getChineseNumberCharValue(c);
if (digit == 10) {
if (lastUnit == 0) {
value += 10;
} else {
value += lastUnit * 10;
lastUnit = 0;
}
} else if (digit > 0) {
if (lastUnit == 0) {
value += digit;
} else {
value += lastUnit * digit;
lastUnit = 0;
}
} else {
int unit = getChineseNumberUnitValue(c);
if (unit > lastUnit) {
lastUnit = unit;
} else {
value += lastUnit;
lastUnit = unit;
}
}
}
if (lastUnit != 0) {
value += lastUnit;
}
return value;
}
private static int getChineseNumberCharValue(char c) {
for (int i = 0; i < CHINESE_NUMBER_CHAR.length; i++) {
if (c == CHINESE_NUMBER_CHAR[i].charAt(0)) {
return i;
}
}
return -1;
}
private static int getChineseNumberUnitValue(char c) {
for (int i = 0; i < CHINESE_NUMBER_UNIT.length; i++) {
if (c == CHINESE_NUMBER_UNIT[i].charAt(0)) {
return CHINESE_NUMBER_UNIT_VALUE[i];
}
}
return 0;
}
@Override
public int compare(String s1, String s2) {
Matcher matcher1 = Pattern.compile(CHINESE_NUMBER_PATTERN).matcher(s1);
Matcher matcher2 = Pattern.compile(CHINESE_NUMBER_PATTERN).matcher(s2);
int result = 0;
while (matcher1.find() && matcher2.find() && result == 0) {
String str1 = matcher1.group();
String str2 = matcher2.group();
int value1 = getChineseNumberValue(str1);
int value2 = getChineseNumberValue(str2);
result = Integer.compare(value1, value2);
}
if (result == 0) {
result = s1.compareTo(s2);
}
return result;
}
}
```
这个类