c#模拟js escape方法的简单实例
程序员文章站
2024-02-15 20:30:52
复制代码 代码如下:public static string escape(string s) &nb...
复制代码 代码如下:
public static string escape(string s)
{
stringbuilder sb = new stringbuilder();
byte[] ba = system.text.encoding.unicode.getbytes(s);
for (int i = 0; i < ba.length; i += 2)
{
if (ba[i + 1] == 0)
{
//数字,大小写字母,以及"+-*/._"不变
if (
(ba[i] >= 48 && ba[i] <= 57)
|| (ba[i] >= 64 && ba[i] <= 90)
|| (ba[i] >= 97 && ba[i] <= 122)
|| (ba[i] == 42 || ba[i] == 43 || ba[i] == 45 || ba[i] == 46 || ba[i] == 47 || ba[i] == 95)
)//保持不变
{
sb.append(encoding.unicode.getstring(ba, i, 2));
}
else//%xx形式
{
sb.append("%");
sb.append(ba[i].tostring("x2"));
}
}
else
{
sb.append("%u");
sb.append(ba[i + 1].tostring("x2"));
sb.append(ba[i].tostring("x2"));
}
}
return sb.tostring();
}