网上看到的一种方法,思路非常的简单,手痒就用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;
}
}
}