开发者

Java escaping chars that already exist in the string

开发者 https://www.devze.com 2023-04-07 10:52 出处:网络
I need to escape chars that exist within a string but the escape chars are part of the escape code ie.

I need to escape chars that exist within a string but the escape chars are part of the escape code ie.

    Map<String, String> escapeChars = new HashMap<String, String>();
        escapeChars.put("^", "^94;");
        escapeChars.put("%", "^37;");
        escapeChars.put("'", "^39;");

    public Stri开发者_JAVA技巧ng findEscapeChars(String x) {
    for(Map.Entry<String, String> entry : escapeChars.entrySet()) {
        if(x.contains(entry.getKey()) ) {   
            x = x.replaceAll(entry.getKey(), entry.getValue());
        }
    }
    return x;
    }

    //result should match
    assertEquals("^37;", findEscapeChars("%")); //example of the caret symbol escaping
    assertEquals("^37; 1 2 ^39; ^94; 4 ^37;", findEscapeChars("% 1 2 ' ^ 4 %"));

It really needs to done in one loop and only one if condition. The problem is that the hash map doesn't traverse in a certain order therfore the caret symbol could try escape itself in the string. It seems to be tricky without numerous loops and if conditions, a simple solution would be ideal.

Thanks D


I'm going to assume you only need to escape a single character at a time. Then you can do:

public String findEscapeChars(String original) {
    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < original.length(); i++)
    {
        char c = original.charAt(i);
        String escaped = escapeMap.get(c);
        if (escaped != null)
        {
            builder.append(escaped);
        }
        else
        {
            builder.append(c);
        }
    }
    return builder.toString();
}

Note that unless you really need to have the dynamic nature of a map, a simple switch would probably be simpler and more efficient.


First, if you need order in map use LinkedHashMap instead. Second, you even can solve everything without maps at all but using regular experession with lookahead. See http://download.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html

0

精彩评论

暂无评论...
验证码 换一张
取 消