将数字转换为汉字

网上看到的一种方法,思路非常的简单,手痒就用c#写了一遍:

思想简要: 
1.数字对应的转换成汉字,这其中不考虑任何情况只是简单的转换:如1000 转换为“一千零百零十零”。 
2.对某些特别的情况进行处理。 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.Win32;

namespace _0902
{
    class Program
    {
        static void Main(string[] args)
        {
            while (true)
            {
                int num = Convert.ToInt32(Console.ReadLine());
                Console.WriteLine(Translate(num));
            }
        }

        static string Translate(int num)
        {
            string[] numStrings = { "零", "一", "二", "三", "四", "五", "六", "七", "八", "九" };
            string[] weightStrings = {"", "十", "百", "千", "万", "十", "百", "千", "亿", "十", "百", "千"};
            string str = Convert.ToString(num);//转换是首位的0会丢弃,如028->变为"28"
            string result = "";
            for (int i = 0; i < str.Length; i++)
            {
                int numWei = (int) (num/Math.Pow(10, str.Length - i - 1))%10;
                result = result + numStrings[numWei] + weightStrings[str.Length - i-1];
            }

            //对可能出现的"零十零百零千"情况进行处理
            result=Regex.Replace(result, "零[十, 百, 千]", "零");
            //举例:将二千零零八替换成二千零八
            result = Regex.Replace(result, "零+", "零");

            result = Regex.Replace(result,"零([万, 亿])", "$1");
            //对开头结尾出现的一些特殊情况进行转换
            if (result.StartsWith("一十"))
            {
                result = result.Substring(1);
            }

            if (result.EndsWith("零"))
            {
                result = result.Substring(0, result.Length - 1);
            }
            return result;
        }
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值