java簡單轉碼

/**
* 轉碼

* @param src
* @return
*/
public static String escape(String src)
{
int i;
char j;
StringBuffer tmp = new StringBuffer();
tmp.ensureCapacity(src.length() * 6);
// 遍歷,對源字符串每一位進行轉碼
for (i = 0; i < src.length(); i++)
{
j = src.charAt(i);
// 數字,字符不需要轉碼
if (Character.isDigit(j) || Character.isLowerCase(j)
|| Character.isUpperCase(j))
tmp.append(j);
// ascil碼轉碼
else if (j < 256)
{
tmp.append("%");
if (j < 16)
tmp.append("0");
tmp.append(Integer.toString(j, 16));
}
else
// 其他轉碼
{
tmp.append("%u");
tmp.append(Integer.toString(j, 16));
}
}
return tmp.toString();
}


/**
* 解碼

* @param src
* @return
*/
public static String unescape(String src)
{
StringBuffer tmp = new StringBuffer();
tmp.ensureCapacity(src.length());
int lastPos = 0, pos = 0;
char ch;
// 查找%,進行解碼
while (lastPos < src.length())
{
pos = src.indexOf("%", lastPos);
// 是經過轉瑪的字符
if (pos == lastPos)
{
if (src.charAt(pos + 1) == 'u')// 是中文
{
ch = (char) Integer.parseInt(
src.substring(pos + 2, pos + 6), 16);
tmp.append(ch);
lastPos = pos + 6;
}
else
// 是ascil碼
{
ch = (char) Integer.parseInt(
src.substring(pos + 1, pos + 3), 16);
tmp.append(ch);
lastPos = pos + 3;
}
}
else
// 不需要解碼
{
if (pos == -1)
{
tmp.append(src.substring(lastPos));
lastPos = src.length();
}
else
{
tmp.append(src.substring(lastPos, pos));
lastPos = pos;
}
}
}
return tmp.toString();
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章