汉字转阿拉伯数字
//数字
HashMap<Character, Integer> numberMap = new HashMap<Character, Integer>() {{
put('一', 1);
put('二', 2);
put('三', 3);
put('四', 4);
put('五', 5);
put('六', 6);
put('七', 7);
put('八', 8);
put('九', 9);
}};
//单位
HashMap<Character, Integer> unitMap = new HashMap<Character, Integer>() {{
put('十', 10);
put('百', 100);
put('千', 1000);
}};
//单位
HashMap<Character, Integer> unitsMap = new HashMap<Character, Integer>() {{
put('万', 10000);
put('亿', 100000000);
}};
@Test
public void myTest08() {
System.out.println(toNumber01("一"));
System.out.println(toNumber01("十"));
System.out.println(toNumber01("十一"));
System.out.println(toNumber01("一十一"));
System.out.println(toNumber01("二十"));
System.out.println(toNumber01("二十一"));
System.out.println(toNumber01("一百"));
System.out.println(toNumber01("一百零一"));
System.out.println(toNumber01("一百一十一"));
System.out.println(toNumber01("一千"));
System.out.println(toNumber01("一千零一"));
System.out.println(toNumber01("一千一百零一"));
System.out.println(toNumber01("一千一百十一"));
System.out.println(toNumber01("一万"));
System.out.println(toNumber01("一万零一"));
System.out.println(toNumber01("一万一千零一"));
System.out.println(toNumber01("一万一千一百零一"));
System.out.println("二十一万五千: " + toNumber01("二十一万五千"));
System.out.println("二十万: " + toNumber01("二十万"));
System.out.println("二十亿: " + toNumber01("二十亿"));
System.out.println("二十一亿五千万: " + toNumber01("二十一亿五千万"));
}
public long toNumber01(String str) {
char[] chars = str.toCharArray();
//个数
long number = 0;
long unit = 0;
long maxUnit = 0;
//结果 暂时
long temporary = 0;
long result = 0;
for (int i = 0; i < chars.length; i++) {
if (numberMap.containsKey(chars[i])) {
number = numberMap.get(chars[i]);
//判断是否是最后一个
if (i == chars.length - 1) {
temporary += (number + unit);
number = 0;
unit = 0;
continue;
}
}
if (unitMap.containsKey(chars[i])) {
unit = unitMap.get(chars[i]);
maxUnit = unitMap.get(chars[i]);
}
//个数和单位都不为空时开始计算
if (0 != number && 0 != unit) {
temporary += (number * unit);
number = 0;
unit = 0;
}
//判断最后单位
if (unitsMap.containsKey(chars[i])) {
Integer finalUnit = unitsMap.get(chars[i]);
if (maxUnit < unitsMap.get(chars[i])) {
result += ((temporary + number + unit) * finalUnit);
temporary = 0;
number = 0;
unit = 0;
}
maxUnit = unitsMap.get(chars[i]);
}
}
return result + temporary+ (number + unit);
}
测试结果
一 ====1
十 ====10
十一 ====11
一十一 ====11
二十 ====20
二十一 ====21
一百 ====100
一百零一 ====101
一百一十一 ====111
一千 ====1000
一千零一 ====1001
一千一百零一 ====1101
一千一百十一 ====1111
一万 ====10000
一万零 ====10001
一万一千零一 ====11001
一万一千一百零一 ====11101
|