-2

Say I have an array, and I need to print out the info in that array with a certain character in between each string in the array. How would I go about this? I'll provide an example.

Print out array with info seperated by a " | " without hardcoding it ex: yes|no|maybe etc...

public class Responses {
   public static void main(String[] args)

      String[] response = {"yes", "no", "maybe", "perhaps"};

The only way I could think of was hard coding it, but I am not allowed to hard code it so that in the event you take out or add something to the array, it will automatically print out that info as well

EDIT: This is not the same as simply printing an array. It is printing the array with the addition of a character between each string

xingbin
  • 27,410
  • 9
  • 53
  • 103
CaptainMuffenz
  • 81
  • 1
  • 1
  • 10
  • Your edit says it is not a duplicate, yet [one of the answers exactly answers your problem](https://stackoverflow.com/a/34441961/466862) judging by the acceptance of the answer below, hence it is a duplicate. – Mark Rotteveel May 06 '18 at 10:55

1 Answers1

2

Use the build-in function join:

String[] response = {"yes", "no", "maybe", "perhaps"};
System.out.println(String.join("|", response));  // yes|no|maybe|perhaps
xingbin
  • 27,410
  • 9
  • 53
  • 103