簡體   English   中英

C#將ISO-8859-1字符轉換為實體編號

[英]C# convert ISO-8859-1 characters to entity number

我似乎無法弄清楚如何將ISO-8859-1字符(例如é)轉換為實體編號為é的實體é

我希望能夠使用一個字符串,例如:“ SteelDécor”

並將其轉換為:“ Steel D é cor”

假設您不關心HTML中特殊的HTML編碼字符(例如<,&等),則可以對字符串進行簡單循環:

string input = "Steel Décor";
StringBuilder output = new StringBuilder();
foreach (char ch in input)
{
    if (ch > 0x7F)
        output.AppendFormat("&#{0};", (int) ch);
    else
        output.Append(ch);
}
// output.ToString() == "Steel D&#233;cor"

根據您的確切需要,可能需要更改if語句以轉義< 0x20或非字母數字等字符。

HttpUtility.HtmlEncode做到這一點。 它位於System.Web.dll中,盡管如此,例如它不適用於.NET 4客戶端配置文件。

使用LINQ

string toDec(string input)
{
    Dictionary<string, char> resDec =
        (from p in input.ToCharArray() where p > 127 select p).Distinct().ToDictionary(
            p => String.Format(@"&#x{0:D};", (ushort)p));

    foreach (KeyValuePair<string, char> pair in resDec)
        input = input.Replace(pair.Value.ToString(), pair.Key);
    return input;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM