JavaScript has Array.join()
js>[\"Bill\",\"Bob\",\"Steve\"].join(\" and \")
Bill and Bob and Steve
Does Java have anything
An orthodox way to achieve it, is by defining a new function:
public static String join(String joinStr, String... strings) {
if (strings == null || strings.length == 0) {
return "";
} else if (strings.length == 1) {
return strings[0];
} else {
StringBuilder sb = new StringBuilder(strings.length * 1 + strings[0].length());
sb.append(strings[0]);
for (int i = 1; i < strings.length; i++) {
sb.append(joinStr).append(strings[i]);
}
return sb.toString();
}
}
Sample:
String[] array = new String[] { "7, 7, 7", "Bill", "Bob", "Steve",
"[Bill]", "1,2,3", "Apple ][","~,~" };
String joined;
joined = join(" and ","7, 7, 7", "Bill", "Bob", "Steve", "[Bill]", "1,2,3", "Apple ][","~,~");
joined = join(" and ", array); // same result
System.out.println(joined);
Output:
7, 7, 7 and Bill and Bob and Steve and [Bill] and 1,2,3 and Apple ][ and ~,~