Here you go!
I've tried to keep object creation to a minimum.
public class QuickTest {
public static void main(String[] args) {
String[] strs = {"Hello","\"World\"","\\Ooh\\err\\\"Missus\""};
for (int i=0, len=strs.length; i < len ; i++) {
System.out.println(strs[i]+" -> "+escapeString(strs[i]));
}
}
/** Escape string, with minimum creation of objects */
public static String escapeString(String str) {
int esc = 0, len=str.length();
char c;
// Count number of chars that need escaping
for (int i=0; i<len; i++) {
c = str.charAt(i);
if (c == '\\' || c == '\"')
esc++;
}
if (esc > 0) {
// If escaping is necessary, create buffer for new string.
char[] buf = new char[len+esc];
for (int i=0, b=0; i<len; i++) {
c = str.charAt(i);
if (c == '\\' || c=='\"')
buf[b++] = '\\'; // Add preceding escape char.
buf[b++] = c;
}
return new String(buf);
}
// No escaping necessary, just return original string.
return str;
}
} // QuickTest