天天看點

助記符解決長而複雜的商品名稱 C#判斷字元串

有些商品的名稱比較長,放到資料庫中又記不住他的條形碼,這給超市等一些儲備商品的倉庫帶來了一定的煩惱,對某個商品進行盤點,因為這個商品名稱很長輸入浪費很長的時間,就讓助記符幫你解決這個難題。

助記符是什麼呢?就是根據輸入的中文字元擷取拼音的首字母。有人要問了,我的商品名稱要是含有字母或數字怎麼辦?解決方案是按正常字元輸入,至轉換漢字。如果使用者輸入的時因為操作的失誤輸入了非法字元 例如:"/" "."等,會輸出null,頁面會把文本框隐藏。我們就要檢查自己輸入的參數了。

說了那麼多,究竟怎麼樣來實作 擷取漢字拼音的首字母呢? 怎麼把 "中文" 轉化成 "ZW" 呢? 實作 代碼如下:

using System; using System.Text; namespace wicho.User { /// <summary> /// 擷取漢語拼音首字母類 /// CopyRight 2011 Wicho Chiu /// </summary> public class ConvertChinese { private ConvertChinese() { } /// <summary> /// 擷取輸入字元的首字母 /// </summary> /// <param name="chinese">傳遞的字元串</param> /// <example> "中文" 轉換為 "ZW"</example> /// <returns>擷取的字元</returns> public static String Convert(String chinese) { char[] buffer = new char[chinese.Length]; for (int i = 0; i < chinese.Length; i++) { buffer[i] = chinese[i]; int num = System.Convert.ToInt32(chinese[i]); if (chinese[i] >= 'A' && chinese[i] <= 'Z' || chinese[i] >= '0' && chinese[i] <= '9') { //大寫字元和數字正常輸出 buffer[i] = chinese[i]; } else if (chinese[i] >= 'a' && chinese[i] <= 'z') { //把小寫字元轉換為大寫字母 buffer[i] = System.Convert.ToChar(num - 32); } else if (num >= 0 && num <= 47 || num >= 58 && num <= 64 || num >= 91 && num <= 96 || num >= 123 && num <= 127) { //非法字元null來代替,文本框會自動隐藏 buffer[i] = '\0'; } else { buffer[i] = Convert(chinese[i]); } } return new String(buffer); } /// <summary> /// 擷取一個漢字的拼首字母 /// </summary> /// <param name= "chinese "> Unicode格式的一個字元 </param> /// <returns>拼音的首字母</returns> public static char Convert(Char chinese) { Encoding gb2312 = Encoding.GetEncoding("GB2312"); Encoding unicode = Encoding.Unicode; byte[] unicodeBytes = unicode.GetBytes(new Char[] { chinese }); byte[] asciiBytes = Encoding.Convert(unicode, gb2312, unicodeBytes); int n = (int)asciiBytes[0] << 8; n += (int)asciiBytes[1]; //擷取漢字拼音的大寫首字母 if (In(0xB0A1, 0xB0C4, n)) return 'A'; if (In(0XB0C5, 0XB2C0, n)) return 'B'; if (In(0xB2C1, 0xB4ED, n)) return 'C'; if (In(0xB4EE, 0xB6E9, n)) return 'D'; if (In(0xB6EA, 0xB7A1, n)) return 'E'; if (In(0xB7A2, 0xB8c0, n)) return 'F'; if (In(0xB8C1, 0xB9FD, n)) return 'G'; if (In(0xB9FE, 0xBBF6, n)) return 'H'; if (In(0xBBF7, 0xBFA5, n)) return 'J'; if (In(0xBFA6, 0xC0AB, n)) return 'K'; if (In(0xC0AC, 0xC2E7, n)) return 'L'; if (In(0xC2E8, 0xC4C2, n)) return 'M'; if (In(0xC4C3, 0xC5B5, n)) return 'N'; if (In(0xC5B6, 0xC5BD, n)) return 'O'; if (In(0xC5BE, 0xC6D9, n)) return 'P'; if (In(0xC6DA, 0xC8BA, n)) return 'Q'; if (In(0xC8BB, 0xC8F5, n)) return 'R'; if (In(0xC8F6, 0xCBF0, n)) return 'S'; if (In(0xCBFA, 0xCDD9, n)) return 'T'; if (In(0xCDDA, 0xCEF3, n)) return 'W'; if (In(0xCEF4, 0xD188, n)) return 'X'; if (In(0xD1B9, 0xD4D0, n)) return 'Y'; if (In(0xD4D1, 0xD7F9, n)) return 'Z'; return '\0'; } private static bool In(int Low, int High, int Value) { return ((Value <= High) && (Value >= Low)); } } }

效果圖:

助記符解決長而複雜的商品名稱 C#判斷字元串