最后的替换如果看不懂可以一步一步的来做
[Java] 纯文本查看 复制代码 package com.itheima;
public class Test9 {
public static void main(String[] args){
//测试
System.out.println(translate(3500908));
System.out.println(translate(101000001010L));
}
public static String translate(long n){
//定义字符数组存储大写数字写法格式
final char[] number = new char[]
{ '零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖' };
//定义字符数组存储单位
final char[] units = new char[]
{ '圆', '拾', '佰', '仟', '万', '拾', '佰', '仟', '亿', '拾', '佰', '仟'};
//定义一个字符串缓冲区对字符进行存储
StringBuffer sb = new StringBuffer();
int index=0;
long lastNumber = 0;
while(n!=0){
lastNumber = n%10;
sb.insert(0,units[index++]);
sb.insert(0,number[(int) lastNumber]);
n=n/10;
}
System.out.println(sb);
//去零操作,通过正则表达式
return sb.toString().replaceAll("零[拾佰仟]","零").replaceAll("零+亿","亿").replaceAll("零{4}万","零").
replaceAll("零+万","万").replaceAll("零+圆","圆").replaceAll("零+","零")+"整";
}
}
|