最近项目上涉及到 汉字数字转阿拉伯数字 然后用于排序的功能,再其他博主搬运的时候发现大多数代码都不是很精确,所以自己靠笨方法写了一个以供大家参考
public static long item(String item){
long result = 0l;
String [] yi = item.split("亿");
if(yi.length == 2){
//亿
long matcher1 = matcher(yi[0]);
//万
String [] wan = yi[1].split("万");
if(wan.length == 2){
long matcher2 = matcher(wan[0]);
long matcher3 = matcher(wan[1]);
result = matcher2 * 10000 + matcher3;
}else{
result = matcher(wan[0]);
}
result += matcher1 * 100000000;
//没到亿
}else{
//万
String [] wan = item.split("万");
if(wan.length == 2){
long matcher2 = matcher(wan[0]);
long matcher3 = matcher(wan[1]);
result = matcher2 * 10000 + matcher3;
}else{
result = matcher(wan[0]);
}
}
return result;
}
private static long matcher(String item){
long result = 0l;
Pattern pattern = Pattern.compile("[零一二三四五六七八九]?[十百千万亿]?");
Matcher matcher = pattern.matcher(item);
Map<Character,Integer> cnMap = new HashMap<>();
cnMap.put('零',0);
cnMap.put('一',1);
cnMap.put('二',2);
cnMap.put('三',3);
cnMap.put('四',4);
cnMap.put('五',5);
cnMap.put('六',6);
cnMap.put('七',7);
cnMap.put('八',8);
cnMap.put('九',9);
cnMap.put('十',10);
Map<Character,Integer> chMap = new HashMap<>();
chMap.put('十',10);
chMap.put('百',100);
chMap.put('千',1000);
//chMap.put('万',10000);
//chMap.put('亿',100000000);
while(matcher.find()){
String res = matcher.group(0);
if(res.length() == 2){
result += cnMap.get(res.charAt(0))*chMap.get(res.charAt(1));
}else if(res.length() == 1){
if(chMap.containsKey(res.charAt(0))){
result *= chMap.get(res.charAt(0));
}else if(cnMap.containsKey(res.charAt(0))){
result += cnMap.get(res.charAt(0));
}
}
}
return result;
}