Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * The same as {@link java.text.MessageFormat}'s format() method, only more efficient
- * <p>
- * Uses a number between {@code {}'s} to index an object in the given arguments. Null objects are handled by the StringBuilder
- * </p>
- * @param value 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
- * @throws BadFormatException If the value between the { and } is empty, or not an integer
- * @throws IndexOutOfBoundsException If the index if out of range (smaller than 0 or bigger than the array's length)
- */
- public static String format(String value, Object... args) {
- if (value == null) {
- return null;
- }
- if (value.isEmpty()) {
- return value;
- }
- int firstOpenIndex = value.indexOf('{', 0);
- if (firstOpenIndex == -1) {
- return value;
- }
- char[] chars = value.toCharArray();
- int lastCloseIndex = StringHelper.charsLastIndexOf(chars, '}', firstOpenIndex);
- if (lastCloseIndex == -1) {
- if (firstOpenIndex == 0 || chars[firstOpenIndex - 1] != '\\') { // check if the format is escaped using \\{
- throw new BadFormatException("Initial format check - missing closing '}' after the first opening bracket '{' at index " + firstOpenIndex);
- }
- return value;
- }
- int maxIndex = args.length - 1;
- StringBuilder builder = new StringBuilder(value.length() * 2);
- builder.append(value, 0, firstOpenIndex);
- for (int i = firstOpenIndex, end = chars.length, endIndex = end - 1; i < end; i++) {
- char c = chars[i];
- if (c == '{') {
- // last character
- if (i == endIndex) {
- builder.append(c);
- break;
- }
- // escape
- if (i > 0 && chars[i - 1] == '\\') {
- builder.setCharAt(i - 1, '{');
- continue;
- }
- int nextClose = StringHelper.charsIndexOf(chars, '}', i + 1);
- if (nextClose == -1) {
- throw new BadFormatException("Missing a closing '}' after an opening bracket '{' at index " + i);
- // builder.append(chars, i, chars.length - i - 1);
- // break;
- }
- int parseIndex = i + 1;
- if (parseIndex == nextClose) {
- throw new BadFormatException("Value between '{' and '}' was empty! At index " + parseIndex);
- // builder.append('{');
- // continue;
- }
- Integer index = StringHelper.parseInteger(chars, parseIndex, nextClose);
- if (index == null) {
- throw new BadFormatException("Value between '{' and '}' was not an integer! At index " + parseIndex);
- }
- if (index < 0 || index > maxIndex) {
- throw new IndexOutOfBoundsException("The index (" + index + ") was out of range (array size was " + args.length + ')');
- }
- // let the sb handle null objects :)
- builder.append(args[index]);
- i = nextClose;
- }
- else {
- builder.append(c);
- }
- }
- return builder.toString();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement