Check if a string is half width or full width in C#

浪子不回头ぞ 提交于 2019-12-01 21:16:37

According to this document, the normalize method works as expected. It must convert characters to the standard characters, so the binary comparison can be applied correctly.

But if you want a custom conversion that always converts full-width to half-width, you can create a Dictionary to map full-width to half-width characters. This link may be helpful to create this map.

If you want to be sure that the string is in half-width then if it contains any full-width character, it is rejected. Create a string of all full-width characters(Latin and Japanese) then find all characters of the to test string in the full-width characters string.

I wrote isHalfWidthString method for this purpose and added full-width to half-width converter method also. I thought it may be helpful:

    public class FullWidthCharactersHandler
    {
        static Dictionary<char, char> fullWidth2halfWidthDic;
        static FullWidthCharactersHandler()
        {
            fullWidth2halfWidthDic = new Dictionary<char, char>();
            string fullWidthChars = "アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヲンッァィゥェォャュョ゙゚ー0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
            string halfWidthChars = "アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヲンッァィゥェォャュョ゙゚ー0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
            for (int i = 0; i < fullWidthChars.Length; i++)
            {
                fullWidth2halfWidthDic.Add(fullWidthChars[i], halfWidthChars[i]);
            }
        }

        public static bool isHalfWidthString(string toTestString)
        {
            bool isHalfWidth = true;
            foreach (char ch in toTestString)
            {
                if (fullWidth2halfWidthDic.ContainsKey(ch))
                {
                    isHalfWidth = false;
                    break;
                }
            }
            return isHalfWidth;
        }

        public static string convertFullWidthToHalfWidth(string theString)
        {
            StringBuilder sbResult = new StringBuilder(theString);
            for (int i = 0; i < theString.Length; i++)
            {
                if (fullWidth2halfWidthDic.ContainsKey(theString[i]))
                {
                    sbResult[i] = fullWidth2halfWidthDic[theString[i]];
                }
            }
            return sbResult.ToString();
        }
    }

For test use this link.

I updated the code to use Dictionary for better performance.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!