2010-11-25 88 views

回答

3

假设你不关心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,或者非字母数字等,根据您的具体需求。

1

HttpUtility.HtmlEncode做到这一点。它驻留在System.Web.dll中,但不能用于.NET 4 Client Profile。

+1

功能以及它没有。它对字符串进行编码,但不是我正在查找的文本格式。这是我尝试的第一件事。我也没有使用网络的东西。 – tracstarr 2010-11-25 18:37:37

1

使用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; 
} 
相关问题