今天工作,遇到了这个问题:需要将字符串转换为对应的数字。所以就写下了这个算法。自己测试了一些,没有问题。
代码如下。算法利用了递归的方法。传入字符串前应先检查是否可以转换为中文字符串。
` /// <summary>
/// ConvertNumstrToInt辅助函数:转换字符串为数值,用到的比较。
/// </summary>
private static int staticCompareZh_NumChar(char ch1, char ch2)
{
List<char> zh_numChars1 = new List<char> { '零', '一', '二', '三', '四', '五', '六', '七', '八', '九' };
List<char> zh_numChars2 = new List<char> { '十', '百', '千', '万', '亿' };
if (!zh_numChars1.Contains(ch1) && !zh_numChars2.Contains(ch1))
{
if (zh_numChars1.Contains(ch2) || zh_numChars2.Contains(ch2))
return -1;
else
return 0;
}
else if (!zh_numChars1.Contains(ch2) && !zh_numChars2.Contains(ch2))
{
return 1;
}
if (zh_numChars1.Contains(ch1))
{
if (zh_numChars1.Contains(ch2))
return -1;
else
return 0;
}
else
{
//如果两个都在zh_numChars2中需要比较下。
if (zh_numChars2.Contains(ch2))
{
int ch1Index = zh_numChars2.IndexOf(ch1);
int ch2Index = zh_numChars2.IndexOf(ch2);
if (ch1Index > ch2Index)
return 1;
else if (ch1Index == ch2Index)
return 0;
else return -1;
}
else
return 1;
}
}
/// <summary>
/// 递归法将中文代表的数字字符串转换为对应数字。
/// </summary>
/// <param name="zhNumStr"></param>
/// <returns></returns>
public static int ConvertZhNumstrnToInt(string zhNumStr)
{
Dictionary<char, int> dict = new Dictionary<char, int>();
dict.Add('零', 0);
dict.Add('一', 1);
dict.Add('二', 2);
dict.Add('三', 3);
dict.Add('四', 4);
dict.Add('五', 5);
dict.Add('六', 6);
dict.Add('七', 7);
dict.Add('八', 8);
dict.Add('九', 9);
dict.Add('十', 10);
dict.Add('百', 100);
dict.Add('千', 1000);
dict.Add('万', 10000);
dict.Add('亿', 100000000);
if ((zhNumStr.Contains("亿") || zhNumStr.Contains("万") || zhNumStr.Contains("千") || zhNumStr.Contains("亿") || zhNumStr.Contains("百") || zhNumStr.Contains("十")) && zhNumStr.Length > 1)
{
string strEnd = zhNumStr[zhNumStr.Length - 1].ToString();
string strStart = "";
for (int i = zhNumStr.Length - 2; i >= 0; i--)
{
if (staticCompareZh_NumChar(zhNumStr[i], zhNumStr[zhNumStr.Length - 1]) != 1)
{
strEnd.Insert(0, zhNumStr[i].ToString());
strEnd = zhNumStr[i].ToString() + strEnd;
}
else
{
strStart = zhNumStr.Substring(0, i + 1);
break;
}
}
if (strStart == "")
{
strStart = zhNumStr.Substring(0, zhNumStr.Length - 1);
strEnd = zhNumStr[zhNumStr.Length - 1].ToString();
return ConvertZhNumstrnToInt(strStart) * dict[strEnd[0]];
}
else
{
return ConvertZhNumstrnToInt(strStart) + ConvertZhNumstrnToInt(strEnd);
}
}
else
{
int res = 0;
for (int i = 0; i < zhNumStr.Length; i++)
{
switch (zhNumStr[i])
{
case '零':
res += 0;
break;
case '一':
res += 1;
break;
case '二':
res += 2;
break;
case '三':
res += 3;
break;
case '四':
res += 4;
break;
case '五':
res += 5;
break;
case '六':
res += 6;
break;
case '七':
res += 7;
break;
case '八':
res += 8;
break;
case '九':
res += 9;
break;
}
}
return res;
}
}
`
如果有不正确或者可以改进的地方,请告诉我,谢谢。