Can I use String.format() with String array parameter?

Viewed 47

Is it possible to format a string given a variable number of arguments?

For example, if I have String array arg which can be any number of arguments, is it possible to get a formatted string (assuming the message string has the same number of %s as the length of the arg array?)

private static String getValue(String... arg) {
  String value = String.format(message, arg);
}

Thank you.

1 Answers

Generally yes:

String[] d = {"abc", "123", "ddd"};
System.out.printf("%s - %s: %s%n", d);

prints:

abc - 123: ddd

However, it may be better to use static method String.join if you need to get a single string with the same separator:

System.out.println(String.join(": ", d)); // prints abc: 123: ddd
Related