String management - any other efficient way?

I had a requirement when I needed to insert an escape sequence in a given string variable in places where single quotes (') appear . I tried using the split method as well as StringTokenizer , none of them worked for me. Therefore, I developed the logic below. It also fails in several scenarios.

Can someone provide me the easiest way to achieve such a 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(message.indexOf("'")!= -1){
                newMessage=newMessage+message.substring(0,message.indexOf("'"))+"\\'";
                message=message.substring(message.indexOf("'"));
            }else{
                newMessage=newMessage+message;
                message="";
            }
        }
    }
    return newMessage;
}
+3
source share
5 answers

how about this:

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

Or am I misunderstanding your requirement?


: , replace(), replaceAll() ( replace() Pattern.LITERAL), , replaceAll() ( replaceFirst()) . ( ). :

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

. , , , , , .

+7

replaceAll:

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

StringBuilder , . , , .

+1
source
message = message.replaceAll("'", "");
+1
source
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();
+1
source

Source: https://habr.com/ru/post/1789811/


All Articles