Util: Add replace() method for StringBuilders

This commit is contained in:
zzz
2018-03-14 13:33:43 +00:00
parent 9b3082be06
commit 66ee7b563a
2 changed files with 24 additions and 9 deletions

View File

@@ -326,14 +326,7 @@ public class SMTPClient {
}
if (ok) {
// in-memory replace, no copies
int oidx = 0;
while (true) {
int idx = body.indexOf("\r\n.\r\n", oidx);
if (idx < 0)
break;
body.replace(idx, idx + 5, "\r\n..\r\n");
oidx = idx + 6;
}
DataHelper.replace(body, "\r\n.\r\n", "\r\n..\r\n");
//socket.getOutputStream().write(DataHelper.getUTF8(body));
//socket.getOutputStream().write(DataHelper.getASCII("\r\n.\r\n"));
// Do it this way so we don't double the memory

View File

@@ -615,7 +615,7 @@ public class DataHelper {
/**
* Lower-case hex without leading zeros.
* Use toString(byte[] to get leading zeros
* Use toString(byte[]) to get leading zeros
* @param data may be null (returns "00")
*/
public final static String toHexString(byte data[]) {
@@ -2055,4 +2055,26 @@ public class DataHelper {
} catch (IllegalArgumentException iae2) {}
}
}
/**
* Replace all instances of "from" with "to" in the StringBuilder buf.
* Same as String.replace(), but in-memory with no object churn,
* as long as "to" is equal size or smaller than "from", or buf has capacity.
* Use for large Strings or for multiple replacements in a row.
*
* @param buf contains the string to be searched
* @param from the string to be replaced
* @param to the replacement string
* @since 0.9.34
*/
public static void replace(StringBuilder buf, String from, String to) {
int oidx = 0;
while (oidx < buf.length()) {
int idx = buf.indexOf(from, oidx);
if (idx < 0)
break;
buf.replace(idx, idx + from.length(), to);
oidx = idx + to.length();
}
}
}