在編程中,我們經常會遇到漢字助記碼的問題,筆者曾經爲此多次發愁,現總結前輩的好東西,記錄於此,希望能幫助到您,方法有多種,我們應該擇優選擇:
SQL存儲過程如下:
USE [ExpensionDB] GO /****** Object: UserDefinedFunction [dbo].[fun_getZjm] Script Date: 04/20/2014 22:28:02 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ------------------------------------------------ --作者:zhangbc --時間:2014-03-19 --功能:獲取漢字拼音首字母 ------------------------------------------------ ALTER function [dbo].[fun_getZjm](@str nvarchar(4000)) returns nvarchar(4000) as begin declare @word nchar(1),@PY nvarchar(4000) set @PY='' while len(@str)>0 begin set @word=left(@str,1) --如果非漢字字符,返回原字符 set @PY=@PY+(case when unicode(@word) between 19968 and 19968+20901 then (select top 1 PY from ( select 'A' as PY,N'驁' as word union all select 'B',N'簿' union all select 'C',N'錯' union all select 'D',N'鵽' union all select 'E',N'樲' union all select 'F',N'鰒' union all select 'G',N'腂' union all select 'H',N'夻' union all select 'J',N'攈' union all select 'K',N'穒' union all select 'L',N'鱳' union all select 'M',N'旀' union all select 'N',N'桛' union all select 'O',N'漚' union all select 'P',N'曝' union all select 'Q',N'囕' union all select 'R',N'鶸' union all select 'S',N'蜶' union all select 'T',N'籜' union all select 'W',N'鶩' union all select 'X',N'鑂' union all select 'Y',N'韻' union all select 'Z',N'咗' ) T where word>=@word collate Chinese_PRC_CS_AS_KS_WS order by PY ASC) else @word end) set @str=right(@str,len(@str)-1) end return @PY end
C#中處理的助記碼代碼:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BLL { public class getZjm { //馬鑫——M*,有問題 public getZjm() { } public string getChsSpell(string str) { string myStr = ""; for (int i = 0; i < str.Length; i++) { myStr += getSpell(str.Substring(i,1)); } return myStr; } private static string getSpell(string cnChar) { //字符編碼 byte[] arrCN = Encoding.Default.GetBytes(cnChar); if (arrCN.Length > 1) { int area = (short)arrCN[0]; int pos = (short)arrCN[1]; int code = (area << 8) + pos; int[] areacode = { 45217, 45253, 45761, 46318, 46826, 47010, 47297, 47614, 48119, 48119, 49062, 49324, 49896,50371, 50614, 50622, 50906, 51387, 51446, 52218, 52698, 52698, 52698, 52980, 53689, 54481 }; for (int i = 0; i < 26; i++) { int max = 55290; if (i != 25) max = areacode[i + 1]; if (areacode[i] <= code && code < max) return Encoding.Default.GetString(new byte[] { (byte)(65 + i) }); } return "*"; } else return cnChar; } } public class getPY { public getPY() { } public string getPiny(string strText) { string myStr = ""; myStr = "select dbo.fun_getZjm('"+strText+"')"; return SqlHelper.GetSingle(myStr).ToString(); } } }
SqlHeler類,參見:http://zhangbc.blog.51cto.com/6066576/1401228
百聞不如一見,怎麼樣,趕緊動手試試吧,方案一(getZjm())是不完美的,不行你試試吧!