简体   繁体   中英

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#.

 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).

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). 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? ).

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.

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM