开发者

String manipulation - Any other efficient way?

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 split method and also StringTokenizer, neither one worked out for me. So i developed the below mentioned logic. It also fails in a few scenarios

Can anyone provide me a simplest way to achieve such requirement.?

public static String quotesMessage(String message){
    String newMessage="";
    while(message.length()>0){
        if(message.indexOf("'")==0){
            if(!StringUtils.isEmpty(message.substring(0))){
                message = message.substring(1);
            }
        }else{
            if(mes开发者_高级运维sage.indexOf("'")!= -1){
                newMessage=newMessage+message.substring(0,message.indexOf("'"))+"\\'";
                message=message.substring(message.indexOf("'"));
            }else{
                newMessage=newMessage+message;
                message="";
            }
        }
    }
    return newMessage;
}


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.


Use the replaceAll method:

myString.replaceAll("'", "\\'");


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.


message = message.replaceAll("'", "");


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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜