import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DigitUtil {
private static Map<String, Integer> MAP_ALPHA = new HashMap<String, Integer>();
static{
MAP_ALPHA.put("一", 1);
MAP_ALPHA.put("二", 2);
MAP_ALPHA.put("三", 3);
MAP_ALPHA.put("四", 4);
MAP_ALPHA.put("五", 5);
MAP_ALPHA.put("六", 6);
MAP_ALPHA.put("七", 7);
MAP_ALPHA.put("八", 8);
MAP_ALPHA.put("九", 9);
}
/**
* 目前只支持1万亿以下
* @param text
*/
public static long getArabicDigit(String text){
int b=text.length();
if (b>23) {
return 0;
}
long count = 0;
if (text.indexOf("亿")>-1) {//text>1亿
String[]u = text.split("亿");
String num_yi = u[0];
int yi = getThousands(num_yi);
count+=yi*100000000l;
if (u.length>1) {
if (u[1].indexOf("万")>-1) {
String[]v = u[1].split("万");
String num_wan = v[0];
int wan = getThousands(num_wan);
count+=wan*10000;
if (v.length>1) {
String num = v[1];
int p = getThousands(num);
count+=p;
}
}else {
int p = getThousands(u[1]);
count+=p;
}
}
}else if (text.indexOf("万")>-1) {//text<1亿&&text>1万
String[]v = text.split("万");
String num_wan = v[0];
int wan = getThousands(num_wan);
count+=wan*10000;
if (v.length>1) {
String num = v[1];
int p = getThousands(num);
count+=p;
}
}else {//text<1万&&text>0
int p = getThousands(text);
count+=p;
}
return count;
}
/**
* 处理一万以内
*/
public static int getThousands(String text){
text = text.replaceAll("零", "");
int count = 0;
if (text.contains("千")) {
String u = getUnitDigit(text, "千");
text = text.replaceAll(u, "");
if (u.length()>0) {
int qian = MAP_ALPHA.get(u.replaceAll("千", ""));
count+=qian*1000;
}
}
if (text.contains("百")) {
String u = getUnitDigit(text, "百");
text = text.replaceAll(u, "");
if (u.length()>0) {
int bai = MAP_ALPHA.get(u.replaceAll("百", ""));
count+=bai*100;
}
}
if (text.contains("十")) {
String u = getUnitDigit(text, "十");
text = text.replaceAll(u, "");
if (u.length()==0) {
u="一十";
}
if (u.length()>0) {
int shi = MAP_ALPHA.get(u.replaceAll("十", ""));
count+=shi*10;
}
}
if (MAP_ALPHA.keySet().contains(text)) {
int ge = MAP_ALPHA.get(text);
count+=ge;
}
return count;
}
/**
* 获取字符串中的单位前的数
* @param text
* @param unit
* @return
*/
public static String getUnitDigit(String text,String unit) {
String regexp = "[一二三四五六七八九]{1}"+unit;
Pattern pattern = Pattern.compile(regexp, 2);
Matcher matcher = pattern.matcher(text);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
sb.append(matcher.group());
}
return sb.toString();
}
//思路2:遇到零处理时,split”零“,2数相加
public static void main(String[] args) {
String t = "九千零十亿零三百一十万三千零五";
try {
long s = getArabicDigit(t);
System.out.println(s);
} catch (Exception e) {
// e.printStackTrace();
System.out.println("chinese digit not support");
}
}
}