34

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

mkobit
  • 34,772
  • 9
  • 135
  • 134
Leo
  • 1,659
  • 5
  • 20
  • 41

19 Answers19

56

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

Jared Rummler
  • 35,743
  • 18
  • 127
  • 142
Naveen Kumar Alone
  • 7,142
  • 5
  • 32
  • 50
16
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
Achintya Jha
  • 12,267
  • 2
  • 25
  • 38
  • 13
    Please don't concatenate strings, use StringBuilder/Buffer or whatever appropriate. – Radek Skokan Nov 15 '13 at 12:00
  • 2
    I cant believe that 13 ppl actually agreed with String concatenation?! I want to double Radek - use StringBuilder instead – Deian May 27 '15 at 13:54
16

Simple answer:

Arrays.toString(arr);

Marco
  • 1,246
  • 4
  • 17
  • 41
6

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"};

Bernhard Barker
  • 50,899
  • 13
  • 85
  • 122
  • if you are concatenating really BIG strings, then you shouldn't ask i == iMax? in each iteration! Just ALWAYS add a separator and then delete the last one after the loop! – Sauer May 06 '13 at 15:33
  • @Sauer Note that I didn't write that first code sample myself, it's a direct copy-and-paste from the Java API. Do you mean a really big **array**? The size of the strings won't matter for the `i == iMax` check. Also note that checking `i == iMax` is a *really*, **really** fast operation (and you need a check to determine the end of the for-loop in either way, so it may as well be there; note the for-loop does **not** look like this: `for (int i = 0; i != iMax; i++)`). – Bernhard Barker May 06 '13 at 15:41
6

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

cw'
  • 748
  • 1
  • 8
  • 22
4

Do it java 8 way in just 1 line:

String.join("", arr);

VHS
  • 8,698
  • 3
  • 14
  • 38
3

Guava has Joiner utility to resolve this issue:

Example:

String joinWithoutSeparator = Joiner.on("").join(1, 2, 3); // returns "123"
String joinWithSeparator = Joiner.on(",").join(1, 2, 3); // returns "1,2,3"
Tho
  • 17,326
  • 6
  • 51
  • 41
3

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());
 }
spassas
  • 4,208
  • 2
  • 29
  • 37
user96279
  • 31
  • 4
  • 1
    Since you don't need the concurrency, a `StringBuilder` is typically suggested over a `StringBuffer`. Additionally, the body of the loop should probably be `strb.append(String.valueOf(id)).append(delimiter);` so as to completely avoid the `+` on the `String`. – Patrick Aug 12 '14 at 17:15
2

Arrays.toString is formatting the output (added the brackets and commas). you should implement your own method of toString.

public String toString(String[] arr){
    String result = "";
    for(String s : arr)
        result+=s;
    return result;
}

[edit] Stringbuilder is better though. see above.

iGili
  • 703
  • 6
  • 18
2

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)

walv
  • 2,237
  • 2
  • 25
  • 35
2

Using Guava's Joiner (which in r18 internally uses StringBuilder)

String[]  arr= {"1","2","3"};
Joiner noSpaceJoiner = Joiner.on("");
noSpaceJoiner.join(arr))

Joiner is useful because it is thread-safe and immutable and can be reused in many places without having to duplicate code. In my opinion it also is more readable.


Using Java 8's Stream support, we can also reduce this down to a one-liner.

String concat = Stream.of(arr).collect(Collectors.joining());

Both outputs in this case are 123

mkobit
  • 34,772
  • 9
  • 135
  • 134
2

This is a little code of convert string array to string without [ or ] or ,

String[] strArray = new String[]{"Java", "String", "Array", "To", "String", "Example"};

String str = Arrays.toString(strArray);
            str = str.substring(1, str.length()-1).replaceAll(",", "");
  • First convert array to string.
  • Second get text from x to y position.
  • third replace all ',' with ""
DarckBlezzer
  • 3,504
  • 1
  • 33
  • 44
1

take a look at generic method to print all elements in an array

but in short, the Arrays.toString(arr) is just a easy way of printing the content of a primative array.

Community
  • 1
  • 1
Ben
  • 966
  • 2
  • 14
  • 30
  • it is important to note that `Arrays.toString(arr)` does not print the array by itself...it only provides the String to be printed – Logan Murphy Dec 04 '14 at 19:10
0

Object class has toString method. All other classes extending it overrides the toString method so in for arrays also toString is overrided in this way. So if you want your output in your way you need to create your own method by which you will get your desired result.

str="";
for (Integer i:arr){
     str+=i.toString();
}

Hope this helps

refer Why does the toString method in java not seem to work for an array

Community
  • 1
  • 1
Meherzad
  • 7,972
  • 1
  • 26
  • 39
0

Here is a way to do it: Arrays.toString(array).substring(1,(3*array.length-1)).replaceAll(", ","");

Here is a demo class:

package arraytostring.demo;

import java.util.Arrays;

public class Array2String {

        public static void main(String[] args) {

                String[] array = { "1", "2", "3", "4", "5", "6", "7" };
                System.out.println(array2String(array));
                // output is: 1234567
        }

        public static String array2String(String[] array) {

                return Arrays.toString(array).substring(1, (3 * array.length - 1))
                                .replaceAll(", ", "");

        }

}

Scala makes this easier, cleaner and safer:

scala> val a = Array("1", "2", "3")
a: Array[String] = Array(1, 2, 3)

scala> val aString = a.mkString
aString: String = 123

scala> println(aString)
123
0

For those who develop in Android, use TextUtils.

String items = TextUtils.join("", arr);

Assuming arr is of type String[] arr= {"1","2","3"};

The output would be 123

Fahmi Eshaq
  • 75
  • 2
  • 8
0

Arrays.toString() can be used to convert String Array to String. The extra characters can be removed by using Regex expressions or simply by using replace method.

Arrays.toString(strArray).replace(",", "").replace("[", "").replace("]", "");

Java 8 has introduced new method for String join public static String join(CharSequence delimiter, CharSequence... elements)

String.join("", strArray);
0

Example using Java 8.

  String[] arr = {"1", "2", "3"};
  String join = String.join("", arr);

I hope that helps

LittleBigUllah
  • 213
  • 3
  • 8
-1
String newString= Arrays.toString(oldString).replace("[","").replace("]","").replace(",","").trim();
Stephen Rauch
  • 40,722
  • 30
  • 82
  • 105