I\'m confused a bit. I couldn\'t find the answer anywhere ;(
I\'ve got an String array:
String[] arr = [\"1\", \"2\", \"3\"];
then
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.
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
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"
Simple answer:
Arrays.toString(arr);
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
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"};