Concatenating elements in an array to a string

170,947

Solution 1

Use StringBuilder instead of StringBuffer, because it is faster than StringBuffer.

Sample code

String[] strArr = {"1", "2", "3"};
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < strArr.length; i++) {
   strBuilder.append(strArr[i]);
}
String newString = strBuilder.toString();

Here's why this is a better solution to using string concatenation: When you concatenate 2 strings, a new string object is created and character by character copy is performed.
Effectively meaning that the code complexity would be the order of the squared of the size of your array!

(1+2+3+ ... n which is the number of characters copied per iteration). StringBuilder would do the 'copying to a string' only once in this case reducing the complexity to O(n).

Solution 2

Simple answer:

Arrays.toString(arr);

Solution 3

Arrays.toString(arr);

output is [1,2,3] and you storing it to your string . and printing it so you get output [1,2,3].

If you want to get output 123 try this:

public static void main(String[] args) {
    String[] arr= {"1","2","3"};
    String output ="";
    for(String str: arr)
        output=output+str;
    System.out.println(output);


}

Output:

123

Solution 4

Arrays.toString: (from the API, at least for the Object[] version of it)

public static String toString(Object[] a) {
    if (a == null)
        return "null";
    int iMax = a.length - 1;
    if (iMax == -1)
        return "[]";

    StringBuilder b = new StringBuilder();
    b.append('[');
    for (int i = 0; ; i++) {
        b.append(String.valueOf(a[i]));
        if (i == iMax)
            return b.append(']').toString();
        b.append(", ");
    }
}

So that means it inserts the [ at the start, the ] at the end, and the , between elements.

If you want it without those characters: (StringBuilder is faster than the below, but it can't be the small amount of code)

String str = "";
for (String i:arr)
  str += i;
System.out.println(str);

Side note:

String[] arr[3]= [1,2,3] won't compile.

Presumably you wanted: String[] arr = {"1", "2", "3"};

Solution 5

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").

Share:
170,947
Leo
Author by

Leo

Updated on February 01, 2020

Comments

  • Leo
    Leo over 4 years

    I'm confused a bit. I couldn't find the answer anywhere ;(

    I've got an String array:

    String[] arr = ["1", "2", "3"];
    

    then I convert it to a string by:

    String str = Arrays.toString(arr);
    System.out.println(str);
    

    I expected to get the string "123", but I got the string "[1,2,3]" instead.

    How could I do it in java? I'm using Eclipse IDE