import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Student{
public char[] name = new char[]{'無','聊','題'};
public int sid= 12123123;
public static void main(String[] args){
Student stu = new Student();
String strName = new String(stu.name);
System.out.println("1 name:" + strName + " sid:" + stu.sid);
System.out.println("2 Int2Hex:" + spaceStr(strName) + Integer.toHexString(stu.sid));
String uni = stringToUnicode(strName);
System.out.println("3 unicode:" + uni );
String cha = unicodeToString(uni);
System.out.println("4 change:" + cha + " unicode:" + stringToUnicode(cha) );
String sch = String.valueOf(stu.sid);
System.out.println("5 segment:" + cutSegment(cutSegment(sch,2,"-"),6,"-"));
}
//用於計算字符數並對其
public static String spaceStr(String s){
String str = "";
for (int i = 0; i < s.length()*2+2; i++) {
str += " ";
}
return str;
}
//轉換Unicode
public static String stringToUnicode(String s) {
String str = "";
for (int i = 0; i < s.length(); i++) {
int ch = (int) s.charAt(i);
if (ch > 255)
str += "\\u" + Integer.toHexString(ch);
else
str += "\\" + Integer.toHexString(ch);
}
return str;
}
//轉換字符,末位求反
public static String unicodeToString(String s) {
Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))"); //正則表達式
Matcher matcher = pattern.matcher(s);
char ch;
while (matcher.find()) {
ch = (char) (Integer.parseInt(matcher.group(2), 16) ^ 1);//這裏做了最後壹位求反的特殊處理^1
s = s.replace(matcher.group(1), ch + "");
}
return s;
}
//插入分隔符
public static String cutSegment(String s, int i, String strInsert){
StringBuffer buff = new StringBuffer(s);
buff.insert(i,strInsert);
return buff.toString();
}
}