String manipulation - Any other efficient way?

后端 未结 5 640
孤街浪徒
孤街浪徒 2021-01-20 09:52

I had a requirement where i need to insert an escape sequence in a given string variable, at places wherever a single quotes (\') appears. I tried using

相关标签:
5条回答
  • 2021-01-20 10:38
    String in = ...
    StringBuilder out = new StringBuilder(in.length() + 16);
    for (int i=0; i<in.length(); i++) {
        char c = in.charAt(i);
        if (c == '\'') {
            out.append("\\'");
        } else {
            out.append(c);
        }
    }
    
    String result = out.toString();
    
    0 讨论(0)
  • 2021-01-20 10:40
    message = message.replaceAll("'", "");
    
    0 讨论(0)
  • 2021-01-20 10:41

    how about this:

    newMessage.replace("'", "\\'")
    

    Or do I misunderstand your requirement?


    And about the discussions in comments: yes, both replace() and replaceAll() use Regular Expressions use compiled Patterns internally (but replace() uses the flag Pattern.LITERAL), interpreting the pattern as literal value, whereas replaceAll() (and replaceFirst()) both use Regular Expressions. However, the compiled patterns are absolutely identical (in this case). Try it yourself:

    Pattern literal = Pattern.compile("'",Pattern.LITERAL);
    Pattern regular = Pattern.compile("'");
    

    Add a breakpoint after these assignments and take a closer look at these two compiled patterns. You will find that all of their field values are identical, so in this case at least, no it doesn't make any difference performance-wise.

    0 讨论(0)
  • 2021-01-20 10:45

    I would use a StringBuilder object rather than manually concatinating the strings. At least you would get some performance improvement out of that if your strings are large.

    0 讨论(0)
  • 2021-01-20 10:48

    Use the replaceAll method:

    myString.replaceAll("'", "\\'");
    
    0 讨论(0)
提交回复
热议问题