Java equivalent of Python repr()?

后端 未结 9 1867
醉酒成梦
醉酒成梦 2020-12-18 18:18

Is there a Java method that works like Python\'s repr? For example, assuming the function were named repr,

\"foo\\n\\tbar\".repr()

would re

9条回答
  •  隐瞒了意图╮
    2020-12-18 19:05

    don't think there's a specific method -- but this'll solve it without commons lang:

    public class test {
    
    public test() throws Exception {
        byte[] hello = "hello\n\tworld\n\n\t".getBytes();
        System.out.println(new String(hexToByte(stringToHex(hello).replaceAll("0a", "5c6e")
                                                                  .replaceAll("09", "5c74"))));
    }
    
    public static void main(String[] args) throws Exception {
        new test();
    }
    
    public static String stringToHex(byte[] b) throws Exception {
        String result = "";
        for (int i = 0; i < b.length; i++) {
            result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
        }
        return result;
    }
    
    public static byte[] hexToByte(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
        }
        return data;
    }
    

    }

提交回复
热议问题