# 特殊名字 NCR 編碼 ###### tags: `實作功能` Unicode是以u/進行分割,而NCR是以&;#進行分割。後面數字字母內容是一樣的 [請問轉碼問題](https://social.msdn.microsoft.com/Forums/zh-TW/201b88cb-3e73-4d97-9f5c-bfdded519b7c/3553121839366813090821839389881228812288amp20227-gt-20227?forum=236) [Numeric character reference - Wiki](https://en.wikipedia.org/wiki/Numeric_character_reference) <iframe width="100%" height="475" src="https://dotnetfiddle.net/Widget/6rINdS" frameborder="0"></iframe> 程式 ``` using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Web; public class Program { public static void Main() { var nameList = new List<string>(){ "鄭淳瀞", "綉巧伃", "洪綉婷" }; // 將名字中的 NCR編碼 轉換為中文 foreach (var name in nameList) { // 判斷是否有 NCR 編碼 if (!Regex.IsMatch(name, ".*&#\\d+;")) continue; // 先把原本的 name 暫存 var newName = name; // 檢查是不是有多筆 NCR 編碼 int ncrCodeCount = name.ToCharArray().Where(c => c == '&').Count(); Console.WriteLine("這個名字有幾筆 NCR 編碼: " + ncrCodeCount); // 可能有多個 NCR 編碼 for (int i = 0; i < ncrCodeCount; i++) { // 找出 NCR 編碼的開頭與結尾 var ncrCodeStart = newName.IndexOf("&"); var ncrCodeEnd = newName.IndexOf(";"); var ncrCodeLegnth = ncrCodeEnd - ncrCodeStart+1;// NCR 編碼字串長度 var ncrCode = newName.Substring(ncrCodeStart, ncrCodeLegnth); Console.WriteLine("開頭Index: " + ncrCodeStart); Console.WriteLine("結尾Index: " + ncrCodeEnd); Console.WriteLine("編碼字串長度: " + ncrCodeLegnth); Console.WriteLine("編碼字串: " + ncrCode); // 將對應的 NCR 編碼取代掉 newName = newName.Replace(ncrCode, HttpUtility.HtmlDecode(ncrCode)); } Console.WriteLine("替換前的名字: " + name); Console.WriteLine("替換後的名字: " + newName + "\r\n"); } } } ``` 結果 ``` 這個名字有幾筆 NCR 編碼: 1 開頭Index: 2 結尾Index: 9 編碼字串長度: 8 編碼字串: 瀞 替換前的名字: 鄭淳瀞 替換後的名字: 鄭淳瀞 這個名字有幾筆 NCR 編碼: 2 開頭Index: 0 結尾Index: 7 編碼字串長度: 8 編碼字串: 綉 開頭Index: 2 結尾Index: 9 編碼字串長度: 8 編碼字串: 伃 替換前的名字: 綉巧伃 替換後的名字: 綉巧伃 這個名字有幾筆 NCR 編碼: 1 開頭Index: 1 結尾Index: 8 編碼字串長度: 8 編碼字串: 綉 替換前的名字: 洪綉婷 替換後的名字: 洪綉婷 ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up