using System.Collections.Generic;
///
/// 十以内数字转换工具类
///
public static class SimpleNumberConverter
{
private static readonly Dictionary ChineseNumbers = new Dictionary
{
{'零', 0}, {'一', 1}, {'二', 2}, {'三', 3}, {'四', 4},
{'五', 5}, {'六', 6}, {'七', 7}, {'八', 8}, {'九', 9},
{'壹', 1}, {'贰', 2}, {'叁', 3}, {'肆', 4}, {'伍', 5},
{'陆', 6}, {'柒', 7}, {'捌', 8}, {'玖', 9},
{'两', 2} // 特殊处理"两"
};
private static readonly Dictionary GreekNumbers = new Dictionary
{
{"Ⅰ", 1}, {"Ⅱ", 2}, {"Ⅲ", 3}, {"Ⅳ", 4}, {"Ⅴ", 5},
{"Ⅵ", 6}, {"Ⅶ", 7}, {"Ⅷ", 8}, {"Ⅸ", 9}
};
///
/// 将中文数字转换为阿拉伯数字(仅支持1-9)
///
/// 中文数字字符
/// 转换后的阿拉伯数字,转换失败返回-1
public static int ChineseToArabic(char chineseNumber)
{
return ChineseNumbers.TryGetValue(chineseNumber, out int result) ? result : -1;
}
///
/// 将希腊数字转换为阿拉伯数字(仅支持1-10)
///
/// 希腊数字字符串
/// 转换后的阿拉伯数字,转换失败返回-1
public static int GreekToArabic(string greekNumber)
{
return GreekNumbers.TryGetValue(greekNumber, out int result) ? result : -1;
}
///
/// 智能转换数字(支持中文数字和希腊数字,限10以内)
///
/// 要转换的数字字符串
/// 转换后的阿拉伯数字,转换失败返回-1
public static int ToArabic(string number)
{
if (string.IsNullOrEmpty(number))
return -1;
// 尝试直接转换阿拉伯数字
if (int.TryParse(number, out int result) && result >= 0 && result < 10)
return result;
// 尝试转换希腊数字
int greek = GreekToArabic(number);
if (greek != -1)
return greek;
// 尝试转换单个中文数字
if (number.Length == 1)
return ChineseToArabic(number[0]);
return -1;
}
}