/** * Concatenates the given objects into a single {@code String}. This method is more efficient than * concatenating using "+", since only one <code>{@link StringBuilder}</code> is created. * * @param objects the objects to concatenate. * @return a {@code String} containing the given objects. */ public static String concat(Object... objects) { if (Arrays.isNullOrEmpty(objects)) { return null; } StringBuilder b = new StringBuilder(); for (Object o : objects) { b.append(o); } return b.toString(); }
/** * Format with {@link String#format(String, Object...)} the given message iif some args have been * given otherwise juts return the message. * * @param message the string to format * @param args args used to format the message, can be null or empty * @return the formatted string if any args were given */ public static String formatIfArgs(String message, Object... args) { return Arrays.isNullOrEmpty(args) // here we need to format %n but not other % since we do not have arguments. %% is formatted // to % so // replacing % into %% and then format it will have no effect. Nevertheless, we want to // format %n // correctly so we replace all % to %% except if they are followed by a 'n'. ? format(message.replaceAll("%([^n])", "%%$1")) : format(message, args); }
/** * Specifies the delimiter to use to join {@code String}s. * * @param delimiter the delimiter to use. * @return the {@code String}s joined using the given delimiter. */ public String with(String delimiter, String escapeString) { if (delimiter == null) { throw new IllegalArgumentException("Delimiter should not be null"); } if (Arrays.isNullOrEmpty(strings)) { return ""; } String escape = escapeString == null ? "" : escapeString; StringBuilder b = new StringBuilder(); int stringCount = strings.length; for (int i = 0; i < stringCount; i++) { String s = strings[i]; if (s != null) { b.append(escape); b.append(s); b.append(escape); } if (i < stringCount - 1) { b.append(delimiter); } } return b.toString(); }