Advertisement
bobmarley12345

Java efficient string formatter

Feb 12th, 2023
1,201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.13 KB | None | 0 0
  1. /**
  2.  * Similar to {@link java.text.MessageFormat#format(String, Object...)}, only more efficient, and
  3.  * escaping a bracket char is done with the <code>\</code> char, instead of the <code>'</code> char
  4.  * <p>
  5.  *     Malformed formats will be worked around, and no exceptions will be thrown
  6.  * </p>
  7.  * @param format The value to be formatted
  8.  * @param args   The values to splice in
  9.  * @return A string where all of the {...} cases have been replaced with the given arguments
  10.  * @author REghZy/BrakeJetz
  11.  */
  12. public static String format(@Nullable String format, Object... args) {
  13.     int i, j = 0, k, n;
  14.     if (StringUtils.isEmpty(format) || (i = format.indexOf('{')) == -1)
  15.         return format;
  16.     StringBuilder sb = new StringBuilder(format.length() * 2); // buffer of 2x format is typically the best result
  17.     do {
  18.         if (i == 0 || format.charAt(i - 1) != '\\') { // check escape char
  19.             sb.append(format, j, i); // append text between j and before '{' char
  20.             if ((k = format.indexOf('}', i)) != -1) { // get closing char index
  21.                 j = k + 1; // set last char to after closing char
  22.                 if (Parsing.parseInt(format, i + 1, k) && (n = Parsing.getInt()) >= 0 && n < args.length) {
  23.                     sb.append(args[n]); // append content
  24.                 }
  25.                 else {
  26.                     // append content between '{' and '}' with the brackets too
  27.                     sb.append('{').append(format, i + 1, k).append('}');
  28.                 }
  29.                 i = j - 1; // set next search index to j (sub 1 because 1 will be added to i next search)
  30.             }
  31.             else {
  32.                 j = i; // set last char to the last '{' char
  33.             }
  34.         }
  35.         else { // remove escape char
  36.             sb.append(format, j, i - 1); // append text between j and before the escape char
  37.             j = i; // set last index to the '{' char, which was originally escaped
  38.         }
  39.     } while ((i = format.indexOf('{', i + 1)) != -1);
  40.     if (j < format.length()) // append remainder of string
  41.         sb.append(format, j, format.length());
  42.     return sb.toString();
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement