没有加注释。好好看看吧。
能实现功能!
public class Test {
public static void main(String[] args) {
String encodeItem = "\\_b2_U2ab__";
String decodeItem = encode(encodeItem);
System.out.println(encodeItem);
System.out.println(decodeItem);
System.out.println(decode(decodeItem));
}
public static String encode(String encodeItem) {
if (encodeItem == null || encodeItem.length() == 0) {
return null;
}
StringBuilder result = new StringBuilder();
for (int i = 0; i < encodeItem.length(); i++) {
char code = encodeItem.charAt(i);
if (Character.isDigit(code)) {
int codeValue = Character.digit(code, 10);
if (codeValue <= 0) {
result.append(code);
} else {
if ((i + 1) < encodeItem.length()) {
for (int j = 0; j < (codeValue + 1); j++) {
result.append(encodeItem.charAt(i + 1));
}
} else {
result.append(code);
}
}
} else if (code == '_') {
result.append("\\UL");
} else {
result.append(code);
}
if ((i + 1) != encodeItem.length()) {
result.append('_');
}
}
return result.toString();
}
public static String decode(String decodeItem) {
if (decodeItem == null || decodeItem.length() == 0) {
return null;
}
StringBuilder sbItem = new StringBuilder(decodeItem);
for (int i = 0; i < sbItem.length(); i++) {
if (sbItem.charAt(i) == '_' && (i + 2) < sbItem.length()) {
while (sbItem.charAt(i + 1) == '_' && sbItem.charAt(i + 2) == '_') {
sbItem.setCharAt(i + 1, ' ');
i++;
}
}
}
StringBuilder result = new StringBuilder();
String[] code = sbItem.toString().split("_");
for (int i = 0; i < code.length; i++) {
String codeItem = code[i];
if (codeItem.length() == 1) {
result.append(codeItem);
} else if ("\\UL".equals(codeItem)) {
result.append("_");
} else {
result.append(codeItem.length() - 1);
}
}
return result.toString();
}
}
关注