1 回答

TA貢獻1847條經驗 獲得超7個贊
標準化方法按預期工作。它必須將字符轉換為標準字符,這樣二進制比較才能正確應用。
但是,如果您想要始終將全角字符轉換為半角字符的自定義轉換,則可以創建一個字典來將全角字符映射到半角字符。
如果您想確保字符串是半角,那么如果它包含任何全角字符,則會被拒絕。創建一個所有全角字符(拉丁文和日文)的字符串,然后在全角字符串中查找要測試字符串的所有字符。
我isHalfWidthString
為此目的編寫了方法,并添加了全角到半角轉換器方法。我認為這可能會有所幫助:
? 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();
? ? ? ? }
? ? }
- 1 回答
- 0 關注
- 353 瀏覽
添加回答
舉報