java汉字数字转成阿拉伯数字工具
import java.util.HashMap;
import java.util.Stack;
public class ChineseToArabicNumerals {
private static final HashMap<Character, Long> numMap = new HashMap<>();
static {
numMap.put('零', 0L);
numMap.put('一', 1L);
numMap.put('二', 2L);
numMap.put('三', 3L);
numMap.put('四', 4L);
numMap.put('五', 5L);
numMap.put('六', 6L);
numMap.put('七', 7L);
numMap.put('八', 8L);
numMap.put('九', 9L);
numMap.put('十', 10L);
numMap.put('廿', 20L);
numMap.put('卅', 30L);
numMap.put('百', 100L);
numMap.put('千', 1000L);
numMap.put('万', 10_000L);
numMap.put('亿', 100_000_000L);
}
public ChineseToArabicNumerals() {
}
public static long transChineseNum(String num) {
if (num == null || num.length() == 0)
return 0L;
long result = 0;
if ((result = transChineseNumYears(num)) != -1) {
return result;
}
result = 0;
Stack<Long> s = new Stack<>();
for (int i = 0; i < num.length(); i++) {
long curNum = numMap.get(num.charAt(i));
if (s.isEmpty() || curNum < s.peek()) {
s.push(curNum);
} else {
int temp = 0;
while (!s.isEmpty() && s.peek() < curNum) {
temp += s.pop();
}
temp = (temp == 0 ? 1 : temp);
s.push(temp * curNum);
}
}
while (!s.isEmpty()) {
result += s.pop();
}
return result;
}
private static long transChineseNumYears(String num) {
for (char c : num.toCharArray()) {
if (numMap.get(c) >= 10L) {
return -1;
}
}
long result = 0;
long unit = 1;
for (int i = num.length() - 1; i >= 0; i--) {
result += numMap.get(num.charAt(i)) * unit;
unit *= 10;
}
return result;
}
}