[英]How to compare number zero programmatically when the keyboard language is changed from english to other language in C#
I want to compare zero that is coming from TextBox as string for removing it from front in c#. 我想将来自TextBox的零作为字符串进行比较,以将其从C#中的开头删除。
private string RemoveLeadingZeros(string str)//TextBox.Text
{
int index = -1;
for (int i = 0; i < str.Trim().Length; i++)
{
if (str[i] == '0')//This comparison fails if i change the keyboard language from english to some other language ex. chinese
continue;
else
{
index = i;
break;
}
}
return (index != -1) ? str.Substring(index) : "0";
}
So, for example if the string is "0001" it should return 1. This method fails if we change the keyboard language other than English (Example:chinese). 因此,例如,如果字符串为“ 0001”,则它应返回1。如果我们更改键盘语言为英语(例如:中文)以外的其他语言,则此方法将失败。
How can we compare the zero irrespective of the language changed from keyboard from English to some other language? 无论将键盘的语言从英语更改为其他语言,我们如何比较零?
I checked a font containing CJK characters (Microsoft JhengHei on Windows 10), and inferred from it that a Chinese keyboard layout would return full-width numbers (starting at U+FF10). 我检查了包含CJK字符的字体(在Windows 10上为Microsoft JhengHei),并由此推断出中文键盘布局将返回全角数字(从U + FF10开始)。 As other keyboard layouts may provide even different numbers, it would appear that the best choice is to use the char.GetNumericValue()
method (see also What's the deal with char.GetNumericValue? ). 由于其他键盘布局甚至可以提供不同的数字,因此似乎最好的选择是使用char.GetNumericValue()
方法(另请参见char.GetNumericValue处理什么 )。
EDIT: Substring()
with a single parameter returns the same string if the index is 0. Added trimming as in the original post, changed the method name to reflect it, and made it an extension method. 编辑:带有单个参数的Substring()
如果索引为0,则返回相同的字符串。与原始文章中一样,添加了修整,更改了方法名称以反映出来,并使其成为扩展方法。
With that, your method would look as follows: 这样,您的方法将如下所示:
private static string TrimAndRemoveLeadingZeros(this string str)
{
int idx = 0;
if (string.IsNullOrEmpty(str)) return str;
str = str.Trim();
for (int i = 0; i < str.Length; i++)
{
int num = (int)char.GetNumericValue(str[i]);
if (num == 0) idx++;
else break;
}
return str.Substring(idx);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.