I\'m confused a bit. I couldn\'t find the answer anywhere ;(
I\'ve got an String array:
String[] arr = [\"1\", \"2\", \"3\"];
then
Use the Arrays.toString() function. It keeps your code short and readable. It uses a string builder internally, thus, it's also efficient. To get rid of the extra characters, you might chose to eliminate them using the String.replace() function, which, admittedly, reduces readability again.
String str = Arrays.toString(arr).replaceAll(", |\\[|\\]", "");
This is similar to the answer of Tris Nefzger, but without the lengthy substring construction to get rid of the square brackets.
Explanation of the Regex: "|" means any of ", " and "[" and "]". The "\\" tells the Java String that we are not meaning some special character (like a new line "\n" or a tab "\t") but a real backslash "\". So instead of "\\[", the Regex interpreter reads "\[", which tells it that we mean a literal square bracket and do not want to use it as part of the Regex language (for instance, "[^3]*" denotes any number of characters, but none of them should be "3").
Example using Java 8.
String[] arr = {"1", "2", "3"};
String join = String.join("", arr);
I hope that helps
I have just written the following:
public static String toDelimitedString(int[] ids, String delimiter)
{
StringBuffer strb = new StringBuffer();
for (int id : ids)
{
strb.append(String.valueOf(id) + delimiter);
}
return strb.substring(0, strb.length() - delimiter.length());
}
String newString= Arrays.toString(oldString).replace("[","").replace("]","").replace(",","").trim();
Do it java 8 way in just 1 line:
String.join("", arr);
For Spring based projects:
org.springframework.util.StringUtils.arrayToDelimitedString(Object[] arr, String delim)
For Apache Commons users, set of nice join methods:
org.apache.commons.lang.StringUtils.join(Object[] array, char separator)