package com.itheima.test;
import java.util.ArrayList;
import java.util.List;
/**
*
10、 金额转换,阿拉伯数字转换成中国传统形式。
*
* 例如:1010 0000 1010 转换为 壹仟零壹拾亿零壹仟零壹拾圆整
*
*/
public class Test10 {
public static void main(String[] args) {
String s = "2132135123510002200051231234";
String result = convertToChinese(s);
System.out.println(result);
}
/**
* 金额转换 . 阿拉伯-->中文传统
*
* @param s
* @return
*/
private static String convertToChinese(String s) {
char[] unit = { '仟', '佰', '拾' };
char[] split = { '万', '亿' };
char[] num = { '零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖' };
// 1.将s补满
int rNum = s.length() % 4;
if (rNum != 0) {
for (int i = 0; i < 4 - rNum; i++) {
s = "0" + s;
}
}
// 2.把阿拉伯数字转成中文
char[] chars = s.toCharArray();
int index;
for (int i = 0; i < chars.length; i++) {
index = chars[i] - '0';
chars[i] = num[index];
}
// 3.分割 . 添加普通单位以及分割单位
// 1)以4为基础单位对字符数组进行分割
int part = chars.length / 4;
char[][] cs = new char[part][4];
int count = 0;
int partIndex = 0;
for (int i = 0; i < chars.length; i++) {
if (count == 4) {
count = 0;
partIndex++;
}
cs[partIndex][count] = chars[i];
count++;
}
for (char[] cs2 : cs) {
System.out.println(cs2);// --------------------------------------------
}
// 2)添加分割单位
List<StringBuffer> sbList = new ArrayList<StringBuffer>();
StringBuffer sb;
int flag = 0;
for (int i = 0; i < part; i++) {
if (part % 2 == 1) {
flag = 0;
} else {
flag = 1;
}
if ((i + flag) % 2 == 0) { // 被分割的部分为偶数位
sb = new StringBuffer();
for (int j = 0; j < 4; j++) {
sb.append(cs[i][j]);
if (j < 3)
sb.append(unit[j]);
}
for (int j = 0; j < (part - i - 1) / 2; j++) {
sb.append(split[1]);
}
sbList.add(sb);
} else {// 被分割的部分为奇数位
sb = new StringBuffer();
for (int j = 0; j < 4; j++) {
sb.append(cs[i][j]);
if (j < 3) {
sb.append(unit[j]);
}
}
sb.append(split[0]);
for (int j = 0; j < (part - i) / 2 - 1; j++) {
sb.append(split[1]);
}
sbList.add(sb);
}
}
sb = new StringBuffer();
for (int i = 0; i < sbList.size(); i++) {
sb.append(sbList.get(i));
}
// 4.将字符串规范化
s = sb.toString();
s = s.replaceAll("零佰|零仟|零拾", "零");
s = s.replaceAll("零{1,}", "零");
s = s.replaceAll("零亿", "亿");
s = s.replaceAll("零万", "万");
if (s.startsWith("零")) {
s = s.substring(1, s.length());
}
s = s + "圆整";
return s;
}
}
|
|