NewbieCoder
NewbieCoder

Reputation: 9

How do I save an array into string without all the data being mixed into a single line?

If I had an array that had store these data

String stringArray[] = {
        "Apple a Day Keep You Away",
        "Banana a Day Keep Her Away",
        "Cat like Dog"};
StringBuffer sb = new StringBuffer();
for (int i = 0; i < stringArray.length; i++) {
    sb.append(stringArray[i]);
}
String str = sb.toString();
System.out.println(str);

I write like this is it going to become Apple a Day Keep You AwayBanana a Day Keep Her AwayCat like Dog Or I need to add and \n like this sb.append(stringArray[i] + "\n") in order to get something I want.

Apple a Day Keep You Away
Banana a Day Keep Her Away
Cat like Dog

Upvotes: 0

Views: 150

Answers (2)

user16072798
user16072798

Reputation:

Since Java 8 you can use String.join method:

String stringArray[] = {
        "Apple a Day Keep You Away",
        "Banana a Day Keep Her Away",
        "Cat like Dog"};

String str = String.join("\n", stringArray);

System.out.println(str);

Output:

Apple a Day Keep You Away
Banana a Day Keep Her Away
Cat like Dog

Upvotes: 0

Yoni
Yoni

Reputation: 1430

Instead of using a StringBuffer, you could also make use of a StringJoiner to append all strings with a separation character. This also prevents adding an extra new line after your last result

String stringArray[] = {"Apple a Day Keep You Away", "Banana a Day Keep Her Away", "Cat like Dog"};
StringJoiner joiner = new StringJoiner("\n");
for(int i = 0; i < stringArray.length; i++) {
    joiner.add(stringArray[i]);
}
String str = joiner.toString();
System.out.println(str);

You could even make use of the streaming api and append your results there with a newline.

String stringArray[] = {"Apple a Day Keep You Away", "Banana a Day Keep Her Away", "Cat like Dog"};

String str = Arrays.stream(stringArray).collect(Collectors.joining("\n"));
System.out.println(str);

Upvotes: 1

Related Questions