public class EncodeAndDecode {
/**
* 译码
*
* @param str
* 要译32313133353236313431303231363533e58685e5aeb931333365653236码的字符串
* @return 译码后的字符串
*/
public String encode(String str) throws StringLenException{
StringBuilder sb = new StringBuilder();
if(null == str) {
throw new StringLenException("字符串末初始化!");
}
int n = str.length();
if(n <=0) {
throw new StringLenException("字符串不能为空!");
}
char c = 0;
int k = 0;
for (int i = 0; i
// 获得当前字符
c = str.charAt(i);
if (c >= '1' && c <= '9' && i != n-1) { // c是1-9的数字, 且i
k = c -'0' + 1;
for(int j=0; j
sb.append(str.charAt(i+1));
}
} else if (c == '_') { // c除1-9,且为”_” 转换为”\Ul”
sb.append("\\UL");
}else{ //其余 复制该字符
sb.append(c);
}
sb.append("_");
}
return sb.deleteCharAt(sb.length()-1).toString();
}
/**
* 解码
*
* @param str
* 要解码的字符串
* @return 解码后的字符串
*/
public String decode(String str) {
StringBuilder sb = new StringBuilder();
if(null == str) {
throw new StringLenException("字符串末初始化!");
}
if(sb.length() <=0) {
throw new StringLenException("字符串不能为空!");
}
String strs[] = str.split("_");
char c = 0;
int k = 0;
int n = strs.length;
if(n == 1) {
sb.append(str);
} else {
for(int i=0; i
k = strs[i].length();
c = strs[i].charAt(0);
if(1 ==k) { // k==1, 将该字符原样复原
sb.append(c);
} else { // k>1,
if(strs[i].equals("\\UL")) {//strs[i] == ”\Ul”, 转换为”_”
sb.append("_");
} else { // strs[i] != ”\Ul”, 转换为k(k = strs[i].length()-1)
sb.append(k-1);
}
}
}
}
return sb.toString();
}
/**
* @param args
*/
public static void main(String[] args) {
String s = "24ab_2t2";
// String s = "04ab_2t2";
// String s = "1a0b_2t2";
// String s = "aaab_2t2";
// String s = "24ab_2335t2";
// String s = "240ab_";
/*EncodeAndDecode encode = new EncodeAndDecode();
String s1 = encode.encode(s);
System.out.println("encode:" + s1);
String s2 = encode.decode(s1);
System.out.println("decode:" + s2);
*/
}
}