-3

Given an array of numbers (integers) how would I go about converting it to a string.

I am from JS so in we normally do :

[1 , 2 , 3 , 4 , 5].join(separator)

But Java doesn't seem to do that.

I tried :

 array.join(" ")

But that throws an error on that it cannot find symbol.


Here is the code :

class Conv {
    public static String findOut(int[] arr) {
        return arr.join(" ");
    }
}
Muhammad Salman
  • 433
  • 6
  • 18

5 Answers5

3

Arrays#toString

Java does not provide a join method for arrays. Utility methods can be found in the Arrays class. For example Arrays.toString(values) (documentation) which returns a String in the following format:

[1, 5, 15, 2]

So

String result = Arrays.toString(values);

StringJoiner

However, you explicitly want the following format:

1 5 15 2

Therefore, use the StringJoiner class (documentation):

StringJoiner sj = new StringJoiner(" ");
for (int value : values) {
    sj.add(value);
}
String result = sj.toString();

Stream API

Or use the Stream API (documentation) to achieve the same result but in a more functional-style:

String result = Arrays.stream(values)  // IntStream
    .mapToObj(Integer::toString)       // Stream<String>
    .collect(Collectors.joining(" ");  // String
Zabuzard
  • 25,064
  • 8
  • 58
  • 82
  • 1
    another option would be `Arrays.toString(arr) .replaceAll("\\[|]", "") .replace(",", " ");` or `String.join(" ", IntStream.of(arr) .mapToObj(Integer::toString).collect(Collectors.toList()));`. Though the best approach i believe is the `joining` collector you're using ;-) – Ousmane D. Jun 14 '18 at 14:31
2

There's no join method on arrays, instead you can use the stream API's joining collector:

Arrays.stream(arr)
      .mapToObj(Integer::toString)
      .collect(Collectors.joining(" "));
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
1
    String out = "";
    for(int i = arr.length){
        out = out+arr[i];
    }

I think that is what you want

FunkyFelix
  • 19
  • 3
1

You can use Arrays.toString(int[] a) method.

int[] a = { 1, 2, 3, 4, 5 };
String b = Arrays.toString(a);
System.out.println(b);

It will print [1, 2, 3, 4, 5]

Later you can modify the string for what you want.

Don't forget to import java.util.Arrays.

You can see it at the java documentation

LucasDelboni
  • 119
  • 1
  • 4
0

Bit late to the party here, but in case you're stuck on a pre 1.8 version of java (stream, StringJoiner etc only exist since 1.8), you can just loop through your array and append to a String. I put in a ternary operator to not add the space at the end as I assume you don't want that:

String result = "";
for (int i = 0; i < arr.length; i++) {
    result += (i == arr.length - 1) ? arr[i] : arr[i] + " ";
}
achAmháin
  • 4,176
  • 4
  • 17
  • 40