Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Similar to {@link java.text.MessageFormat#format(String, Object...)}, only more efficient, and
- * escaping a bracket char is done with the <code>\</code> char, instead of the <code>'</code> char
- * <p>
- * Malformed formats will be worked around, and no exceptions will be thrown
- * </p>
- * @param format The value to be formatted
- * @param args The values to splice in
- * @return A string where all of the {...} cases have been replaced with the given arguments
- * @author REghZy/BrakeJetz
- */
- public static String format(@Nullable String format, Object... args) {
- int i, j = 0, k, n;
- if (StringUtils.isEmpty(format) || (i = format.indexOf('{')) == -1)
- return format;
- StringBuilder sb = new StringBuilder(format.length() * 2); // buffer of 2x format is typically the best result
- do {
- if (i == 0 || format.charAt(i - 1) != '\\') { // check escape char
- sb.append(format, j, i); // append text between j and before '{' char
- if ((k = format.indexOf('}', i)) != -1) { // get closing char index
- j = k + 1; // set last char to after closing char
- if (Parsing.parseInt(format, i + 1, k) && (n = Parsing.getInt()) >= 0 && n < args.length) {
- sb.append(args[n]); // append content
- }
- else {
- // append content between '{' and '}' with the brackets too
- sb.append('{').append(format, i + 1, k).append('}');
- }
- i = j - 1; // set next search index to j (sub 1 because 1 will be added to i next search)
- }
- else {
- j = i; // set last char to the last '{' char
- }
- }
- else { // remove escape char
- sb.append(format, j, i - 1); // append text between j and before the escape char
- j = i; // set last index to the '{' char, which was originally escaped
- }
- } while ((i = format.indexOf('{', i + 1)) != -1);
- if (j < format.length()) // append remainder of string
- sb.append(format, j, format.length());
- return sb.toString();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement