如何获得香港语言年(文化信息:zh-hk)

时间:2016-09-21 06:47:41

标签: c# .net

我想匹配香港语言中的字符串 我在香港语言中有月份和年份

二零一六年六月份  ===>June 2016
二零一五年六月份  ===>June 2015

我使用文化信息(zh-HK)来获得月份

enter image description here

但如何获得一年?请帮忙

1 个答案:

答案 0 :(得分:3)

基本上,您需要创建一个字典,该字典使用中文字符作为键,相应的数字作为值:

var dict = new Dictionary<String, String>() {
    {"零", "0"},
    {"一", "1"},
    {"二", "2"},
    {"三", "3"},
    {"四", "4"},
    {"五", "5"},
    {"六", "6"},
    {"七", "7"},
    {"八", "8"},
    {"九", "9"},
    {"十", "1"} // this is needed for the months to work. If you know Chinese you would know what I mean
};

然后,使用分隔符“年”分割输入字符串:

string[] twoParts = inputString.Split('年');

循环浏览第一部分的每个字符。使用您创建的词典,您可以轻松地从2016获取"二零一六"

对于第二部分,检查最后是否存在"份"。如果是,则将其子串。 (有时可以写几个月没有“份”)。在那之后,再做一个子串来摆脱“月”。

现在,您再次使用上面的字典将"十二"转换为"12"

现在您有了年份和月份,只需创建DateTime的新实例!

这是完整的代码:

string inputString = ...;
var dict = new Dictionary<String, String>() {
    {"零", "0"},
    {"一", "1"},
    {"二", "2"},
    {"三", "3"},
    {"四", "4"},
    {"五", "5"},
    {"六", "6"},
    {"七", "7"},
    {"八", "8"},
    {"九", "9"},
    {"十", "1"} // this is needed for the months to work. If you know Chinese you would know what I mean
};

string[] twoParts = inputString.Split ('年');
StringBuilder yearBuilder = new StringBuilder ();
foreach (var character in twoParts[0]) {
    yearBuilder.Append (dict [character.ToString ()]);
}

string month = twoParts [1];
if (month [month.Length - 1] == '份') {
    month = month.Substring (0, month.Length - 1);
}
month = month.Substring (0, month.Length - 1);
StringBuilder monthBuilder = new StringBuilder ();

foreach (var character in month) {
    monthBuilder.Append (dict [character.ToString ()]);
}

var date = new DateTime (Convert.ToInt32 (yearBuilder.ToString()), Convert.ToInt32 (monthBuilder.ToString()), 1);
Console.WriteLine (date);

编辑:

我刚刚意识到,如果月份是十月,这不起作用,在这种情况下,它将解析为一月。要解决此问题,您需要在几个月内使用单独的字典。由于SE编辑器不允许我输入太多的汉字,我会尽量告诉你想在评论中加入这本词典。

解析月份时,请使用新词典。所以现在月份解析代码将如下所示:

month = month.Substring (0, month.Length - 1);
string monthNumberString = newDict[month];

不需要为每个循环。