-3

I have a string array (not arraylist), what is the best way to print it into a new string with whitespace separating them, lets say

String array = {"a", "b", "c"};

I want to print it to "a b c", how can I do that?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Schuld
  • 7
  • 4

3 Answers3

1

You can use Arrays.toString(String[]). It will return a String of the format:

[a, b, c]

Then you can simply replace "[", "]", "," with an empty string, and you'll be left with only the whitespaces:

String[] str = { "a", "b", "c" };
System.out.println(Arrays.toString(str).
              replace("[", "").replace("]","").replace(",", ""));

Output is: a b c

Of course this will only work if your strings doesn't contain one of those characters!

Ori Lentz
  • 3,668
  • 6
  • 22
  • 28
0
public String printOutput(String[] input){
     String output="";
      for(String text :  input){
      output+=" "+text;
      }
   return output;
}
sathya_dev
  • 513
  • 3
  • 15
0

You can use this code to get String with whitespace.

String[] array = {"a", "b", "c"};
String output = "";
for (int i = 0; i < array.length; i++) {
    output += array[i] + " ";
}
Tom
  • 16,842
  • 17
  • 45
  • 54
Prashant Bhoir
  • 900
  • 6
  • 8