-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
  • 34,719
  • 24
  • 185
  • 251
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,670
  • 6
  • 21
  • 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
  • 15,514
  • 17
  • 42
  • 51
Prashant Bhoir
  • 885
  • 6
  • 8