忽略转义 - Java

时间:2014-06-03 06:29:23

标签: java escapestring

我一直在尝试创建一种用Java编码字符串的方法,但是我遇到了很大的障碍。

我的问题是我无法忽略\ n \ u \等转义符。 (它们也被编码。)

我花了3个小时解决这个问题,这是我的代码。

public Object encode() throws EncodingException {
    String encoded = "";
    if (!isEncoded) {
        int i = 0;
        char[] alpha = (this.value.toString().toCharArray());

        while (!(i >= alpha.length)) {
            i++;
            try {
                if(!(alpha[i - 1] == '\\')){
                    encoded = encoded
                            + SerializeEncoding.encoding.encodings.get(
                                    new String(new char[] { alpha[i - 1] }))
                                    .toString();
                }else{
                    encoded = encoded
                    + alpha[i - 1] + alpha[i];
                    i++;
                }

            } catch (NullPointerException e) {
                encoded = encoded
                        + new String(new char[] { alpha[i - 1] })
                                .toString();
            }

        }
        encodedValue = (Object) encoded;
        isEncoded = true;
        log = encodedValue;
        return (Object) encodedValue;
    } else {
        throw new EncodingException("Already encoded");
    }
}

谢谢 Curlip

PS。告诉我,如果我错过了什么。

2 个答案:

答案 0 :(得分:1)

我对你的要求不是很清楚,你可以通过遍历String来处理java中的所有特殊字符

public static void main(String[] args) {
    String before = "test\ntest1\n";
    final StringBuilder result = new StringBuilder();
    final StringCharacterIterator iterator = new StringCharacterIterator(before);
    char character =  iterator.current();
     while (character != CharacterIterator.DONE ){
             // do whatever you want to do with the char... I am just removing the \n
         if (character == '\n') {   
             character = iterator.next(); 
         } else {
             result.append(character);               
         }
         character = iterator.next();
     }

    System.out.println(result.toString());
}

答案 1 :(得分:0)

一个选项可能如下。请优化代码。

String before = "test\ntest1\n";
         String after = "";
            String [] str = before.split("\n");
            for (String string : str) {
                after = after+encode(string)+"\n";
            }