我似乎无法弄清楚如何将ISO-8859-1字符(如é)转换为其实体编号为é
。C#将ISO-8859-1字符转换成实体编号
我希望能够获得一个字符串,如:“钢铁装饰”
,并把它转化为:“钢铁d é
心病”
我似乎无法弄清楚如何将ISO-8859-1字符(如é)转换为其实体编号为é
。C#将ISO-8859-1字符转换成实体编号
我希望能够获得一个字符串,如:“钢铁装饰”
,并把它转化为:“钢铁d é
心病”
假设你不关心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écor"
的if
声明可能需要改变也转义字符< 0x20
,或者非字母数字等,根据您的具体需求。
HttpUtility.HtmlEncode
做到这一点。它驻留在System.Web.dll中,但不能用于.NET 4 Client Profile。
使用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;
}
功能以及它没有。它对字符串进行编码,但不是我正在查找的文本格式。这是我尝试的第一件事。我也没有使用网络的东西。 – tracstarr 2010-11-25 18:37:37