ASP.NET(C#)将汉字数字转换成阿拉伯数字
Code
struct Number
{
public int this[char c]
{
get
{
switch (c)
{
case'一':return 1;
case'二':return 2;
case'三':return 3;
case'四':return 4;
case'五':return 5;
case'六':return 6;
case'七':return 7;
case'八':return 8;
case'九':return 9;
case'零':return 0;
default:return -1;
}
}
}
}
/// <summary>
///
/// </summary>
struct Unit
{
public int this[char c]
{
get
{
switch (c)
{
case'十':return 10;
case'百':return 100;
case'千':return 1000;
case'万':return 10000;
case'亿':return 100000000;
default:return 1;
}
}
}
}
public long Parse(string cnum)
{
Unit unit;
Number number;
cnum = Regex.Replace(cnum, "\\s+", "");
long firstUnit = 1;//一级单位
long secondUnit = 1;//二级单位
long tmpUnit = 1;
long result = 0;
for (int i = cnum.Length - 1; i> -1;--i)
{
tmpUnit = unit[cnum[i]];
if (tmpUnit > firstUnit)
{
firstUnit = tmpUnit;
secondUnit = 1;
continue;
}
else if(tmpUnit > secondUnit)
{
secondUnit = tmpUnit;
continue;
}
result += firstUnit * secondUnit * number[cnum[i]];
}
return result;
}
struct Number
{
public int this[char c]
{
get
{
switch (c)
{
case'一':return 1;
case'二':return 2;
case'三':return 3;
case'四':return 4;
case'五':return 5;
case'六':return 6;
case'七':return 7;
case'八':return 8;
case'九':return 9;
case'零':return 0;
default:return -1;
}
}
}
}
/// <summary>
///
/// </summary>
struct Unit
{
public int this[char c]
{
get
{
switch (c)
{
case'十':return 10;
case'百':return 100;
case'千':return 1000;
case'万':return 10000;
case'亿':return 100000000;
default:return 1;
}
}
}
}
public long Parse(string cnum)
{
Unit unit;
Number number;
cnum = Regex.Replace(cnum, "\\s+", "");
long firstUnit = 1;//一级单位
long secondUnit = 1;//二级单位
long tmpUnit = 1;
long result = 0;
for (int i = cnum.Length - 1; i> -1;--i)
{
tmpUnit = unit[cnum[i]];
if (tmpUnit > firstUnit)
{
firstUnit = tmpUnit;
secondUnit = 1;
continue;
}
else if(tmpUnit > secondUnit)
{
secondUnit = tmpUnit;
continue;
}
result += firstUnit * secondUnit * number[cnum[i]];
}
return result;
}