数字串转中文读法串-Java实现

面试时被问到这个问题,遂查看相关博客,自己也作了相应的实现:

package num2rmb;
public class Num2Rmb3 {
	/**
	 * 处理0,1,2.。9的中文读法的
	 */
	private String[] hanArr = {"零" , "壹" , "贰" , "叁" , "肆" , "伍" , "陆" , "柒" , "捌" , "玖"};
	/**
	 * 10进制的读法
	 */
	private String[] unitArr = {"十" , "百" , "千"};
	public static void main(String[] args) {
		Num2Rmb3 nr = new Num2Rmb3();
		nr.readNumString("1052433768");
//		nr.readNumString("5000");
//		System.out.println(Math.ceil(3.5));   //4.0
	}

	public void readNumString(String numstr)
	{
		StringBuilder sb = new StringBuilder();
		int len = numstr.length();
		int count = 0;
		while (len > 0)    //依次取出最后,以4位字符为标准取子串
		{
			int i = (len - 4) >= 0 ? (len - 4) : 0;
			String temp = numstr.substring(i, len);
			System.out.println(temp);
			String res = processTemp(temp, count);  // 对这四个字符进行处理
			sb.insert(0, res);              //往前将求得的字符串插入sb中
			len -= 4;
			count++;  // 记录这个子串中能组成多少个 4个字符的串

		}
		System.out.println(sb);


	}
	public String processTemp(String temp, int count)
	{
		String res = "";
		int len1 = temp.length();
		// 0042
		// 200
		for (int i = 0; i < len1; i++)
		{
			//将每个字符转成数字
			int num = temp.charAt(i) - 48;
			if (num == 0)  //如果是0
			{
				if (i == (len1 - 1))  //到了子串的最后一个字符
				{
					continue;
				}
				//如果下一个是数字字符不是0
				if (temp.charAt(i + 1) != '0')
				{
					res += hanArr[num];
				}
				else {
					continue;
				}
			}
			else if( i == (len1 - 1) ) {  //不是0,最后一个字符
				res += hanArr[num];
			}
			else  //
			{
				res += hanArr[num] + unitArr[len1 - i - 2];
			}
		}

		if (count == 1)
		{
			res += "万";
		}
		else if (count == 2)
		{
			res += "亿";
		}
		return res;
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值