在.NET中将非ascii(unicode)数字字符串解析为整数 [英] Parse a non-ascii (unicode) number-string as integer in .NET
问题描述
我有一个字符串,其中包含非ASCII格式的数字,例如Unicode孟加拉文数字一号(U + 09E7):"১"
I have a string containing a number in a non-ascii format e.g. unicode BENGALI DIGIT ONE (U+09E7) : "১"
如何在.NET中将其解析为整数?
How do I parse this as an integer in .NET?
注意:我尝试使用 int.Parse()
指定一个以"bn-BD"作为IFormatProvider的孟加拉文化格式.不起作用.
Note: I've tried using int.Parse()
specifying a bengali culture format with "bn-BD" as the IFormatProvider. Doesn't work.
推荐答案
您可以创建一个与旧字符串相同的新字符串,除了将本机数字替换为拉丁十进制数字.可以通过遍历字符并检查 char.IsDigit(char)
的值来可靠地完成此操作.如果此函数返回true,则使用 char.GetNumericValue(char).ToString()
进行转换.
You could create a new string that is the same as the old string except the native digits are replaced with Latin decimal digits. This could be done reliably by looping through the characters and checking the value of char.IsDigit(char)
. If this function returns true, then convert it with char.GetNumericValue(char).ToString()
.
赞:
static class DigitHelper
{
public static string ConvertNativeDigits(this string text)
{
if (text == null)
return null;
if (text.Length == 0)
return string.Empty;
StringBuilder sb = new StringBuilder();
foreach (char character in text)
{
if (char.IsDigit(character))
sb.Append(char.GetNumericValue(character));
else
sb.Append(character);
}
return sb.ToString();
}
}
int value = int.Parse(bengaliNumber.ConvertNativeDigits());
这篇关于在.NET中将非ascii(unicode)数字字符串解析为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!