字符串转化为 HTML 实体? 怎么写最简单?
比如把“你好”输出为:你 好

解决方案 »

  1.   


                string str = "你好";
                StringBuilder sb = new StringBuilder();
                foreach (char c in str)
                    sb.AppendFormat("&#{0};", (int)c);
                Console.WriteLine(sb.ToString());
      

  2.   

    .Net 的不会,不过ASP的我给你写一个Function htmlentities(str)
        Dim a,i,char
        For i = 1 to Len(str)
            char = mid(str, i, 1)
            a=Ascw(char)
            If a > 128 Or a < 0 then
                htmlentities = htmlentities & “&#" & clng(”&h” & hex((Ascw(char)))) & “;"
            Else
                htmlentities = htmlentities & char
            End if
        Next
    End Function
    注意Ascw()函数有可能返回的是长整型数据, 但ASP中默认把它作为非长整形处理,所以需要做处理.转换原理就是微软的操作系统或软件一般运行时的内码都是UNICODE,取ASC码构造成实体即可.另外我这个函数并不单字节字符进行编码.所以可以方便的对一段HTML与汉字的混合字符串进行使用, 用于喜欢出现乱码的地方, 比如发送HTML邮件什么的.