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;
}
source
share