【问题标题】:How to convert(unescape) string to char, for example "\\n" to '\n', in java如何在java中将(unescape)字符串转换为char,例如“\\n”到“\n”
【发布时间】:2013-11-18 13:23:47
【问题描述】:

我正在阅读一些 utf-16 和 ascii 混合文件,例如: \u6b64\u626b\u63cf: abc

我会在 java 中得到“\\u6b64\\u626b\\u63cf:abc”(字符串长度为 29)。 如何将其转换为“\u6b64\u626b\u63cf:abc”(字符串长度为8)?

我知道 Apache Commons 库中有 StringEscapeUtils,但我不喜欢使用外部库。

或者,我可以直接读到“\u6b64\u626b\u63cf:abc”吗?

【问题讨论】:

标签: java escaping


【解决方案1】:

似乎没有通用的库可以使用。 但是我在java的Properties类中找到了这个私有方法,彻底解决了我的问题。

private String loadConvert (char[] in, int off, int len, char[] convtBuf) {
    if (convtBuf.length < len) {
        int newLen = len * 2;
        if (newLen < 0) {
            newLen = Integer.MAX_VALUE;
        }
        convtBuf = new char[newLen];
    }
    char aChar;
    char[] out = convtBuf;
    int outLen = 0;
    int end = off + len;
    while (off < end) {
        aChar = in[off++];
        if (aChar == '\\') {
            aChar = in[off++];
            if(aChar == 'u') {
                // Read the xxxx
                int value=0;
                for (int i=0; i<4; i++) {
                    aChar = in[off++];
                    switch (aChar) {
                      case '0': case '1': case '2': case '3': case '4':
                      case '5': case '6': case '7': case '8': case '9':
                         value = (value << 4) + aChar - '0';
                         break;
                      case 'a': case 'b': case 'c':
                      case 'd': case 'e': case 'f':
                         value = (value << 4) + 10 + aChar - 'a';
                         break;
                      case 'A': case 'B': case 'C':
                      case 'D': case 'E': case 'F':
                         value = (value << 4) + 10 + aChar - 'A';
                         break;
                      default:
                          throw new IllegalArgumentException(
                                       "Malformed \\uxxxx encoding.");
                    }
                 }
                out[outLen++] = (char)value;
            } else {
                if (aChar == 't') aChar = '\t';
                else if (aChar == 'r') aChar = '\r';
                else if (aChar == 'n') aChar = '\n';
                else if (aChar == 'f') aChar = '\f';
                out[outLen++] = aChar;
            }
        } else {
            out[outLen++] = aChar;
        }
    }
    return new String (out, 0, outLen);
}

【讨论】:

    猜你喜欢
    • 2018-07-24
    • 2018-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-27
    • 1970-01-01
    • 1970-01-01
    • 2015-08-07
    相关资源
    最近更新 更多