Java反斜杠编码特殊字符,如引号,制表符,换行符,反斜杠,以使其可解析

时间:2013-12-06 02:26:46

标签: java string

我正在编写获取字符串的Java,如“C:\ Temp \ file.txt”和生成包含这些字符串的C源代码,代码将在稍后编译。所以我需要以一种可以由C编译器解析的形式呈现字符串;我的例子就是“C:\\ Temp \\ file.txt”。当然,字符串也可能有其他特殊字符。

基本上我需要在Java中使用与本答案中讨论的相同的功能:standard c library for escaping a string

NB Python用'repr'提供了这样的东西,我想可能有一个Java库方法。但到目前为止我还没有找到它。提前谢谢。

2 个答案:

答案 0 :(得分:3)

这是我解决问题的代码。非常受欢迎的改进。

package my.package;

public class ParseableStringHelper {

/**
 * http://stackoverflow.com/questions/1029897/comparing-a-char-to-a-code-
 * point
 * 
 * Does not implement Iterator
 */
static class CodePointIterator {

    private final String sequence;
    private int index = 0;

    public CodePointIterator(final String sequence) {
        this.sequence = sequence;
    }

    public boolean hasNext() {
        return index < sequence.length();
    }

    public int next() {
        int codePoint = sequence.codePointAt(index);
        index += Character.charCount(codePoint);
        return codePoint;
    }
}

/**
 * Converts a String to a version that can be parsed by a C or Java compiler
 * when enclosed in double quotes, which requires escaping all special
 * characters by prefixing them with a backslash. Does NOT do anything
 * special for single-quote characters (which are perfectly valid inside a
 * quoted string); always escapes double-quote characters.
 * 
 * http://docs.oracle.com/javase/tutorial/java/data/characters.html
 * 
 * @param internal
 *            String that may have special characters
 * @return String with proper escape sequences for special characters like
 *         backslash and newline.
 */
public static String getParseableVersion(final String internal) {
    StringBuilder sb = new StringBuilder();
    CodePointIterator pointIterator = new CodePointIterator(internal);
    while (pointIterator.hasNext()) {
        int point = pointIterator.next();
        switch (point) {
        case '\b':
            sb.append("\\b");
            break;
        case '\f':
            sb.append("\\f");
            break;
        case '\n':
            sb.append("\\n");
            break;
        case '\r':
            sb.append("\\r");
            break;
        case '\t':
            sb.append("\\t");
            break;
        case '\\':
            // double these up
            sb.append("\\\\");
            break;
        case '"':
            sb.append("\"");
            break;
        default:
            sb.append(Character.toChars(point));
            break;
        }
    }
    return sb.toString();
}

/**
 * Test the helper
 * 
 * @param args
 */
public static void main(String[] args) {
    String[] tests = { "C:\\Temp\\file.txt",
            "This has\tsome special characters\n" };
    for (String t : tests)
        System.out.println("Orig is " + t + ", parseable is \""
                + getParseableVersion(t) + "\"");
  }
}

答案 1 :(得分:1)

我建议你看一下你可能会使用的Apache Commons StringEscapeUtils -

StringEscapeUtils.escapeJava(str); // this will likely work for most cases.