I have this little convenience method that takes an String
array and returns an String
where the values are separated by a provided separator (comma, pipe, etc).
For instance, if given an array with values "abc", "def" and "ghi", and a for separator we passed " | ", the end result would be "abc | def | ghi"
.
This is the method:
public String getArrayAsString(String[] stringArray, String separator) {
StringBuilder finalString = new StringBuilder();
boolean needsSeparator = false;
for (String s : stringArray) {
if (needsSeparator) {
finalString.append(separator);
}
finalString.append(s);
needsSeparator = true;
}
return finalString.toString();
}
Notice that the separator must, as its name implies, separate values, and not be appended or prepended artificially to the final String
. So, for instance, the following would be incorrect return values: "abc | def | ghi | "
or " | abc | def | ghi"
.
I specifically don't like the needsSeparator
flag variable, but without it, the unwanted leading or trailing separators would be added, and then I would need to remove them from the finalString
before returning it, which I also don't find to be very elegant.
Is there a more concise (perhaps more elegant) way to achieve this?