Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I append a newline character for all lines except the last one?

I'm iterating through a HashMap (see my earlier question for more detail) and building a string consisting of the data contained in the Map. For each item, I will have a new line, but for the very last item, I don't want the new line. How can I achieve this? I was thinking I could so some kind of check to see if the entry is the last one or not, but I'm not sure how to actually do that.

Thanks!

like image 553
troyal Avatar asked Jan 15 '09 20:01

troyal


People also ask

Which method is a member that appends a new line character to the end of the string in Java?

AppendLine() ' Append two lines of text. sb. AppendLine(line) sb. AppendLine("The last line of text.") ' Convert the value of the StringBuilder to a string and display the string.

How do you append to next line?

There are several ways to append a new line but most of them are platform dependent that means they work on one platform but not for other (for example appending “\r\n” would give new line on Windows but for Unix we need to append “\n”).

Which method appends a new line character to the end of string?

The AppendLine() method appends the content and add a new line on the end.

What is the symbol used for adding a new content in new line?

Well, the backslash (“\”) in the new line character is called an escape sequence. Escape sequences are used to add anything illegal to a string.


2 Answers

Change your thought process from "append a line break all but the last time" to "prepend a line break all but the first time":

boolean first = true; StringBuilder builder = new StringBuilder();  for (Map.Entry<MyClass.Key,String> entry : data.entrySet()) {     if (first) {         first = false;     } else {         builder.append("\n"); // Or whatever break you want     }     builder.append(entry.key())            .append(": ")            .append(entry.value()); } 
like image 52
Jon Skeet Avatar answered Oct 11 '22 13:10

Jon Skeet


one method (with apologies to Jon Skeet for borrowing part of his Java code):

StringBuilder result = new StringBuilder();  string newline = "";   for (Map.Entry<MyClass.Key,String> entry : data.entrySet()) {     result.append(newline)        .append(entry.key())        .append(": ")        .append(entry.value());      newline = "\n"; } 
like image 44
Joel Coehoorn Avatar answered Oct 11 '22 14:10

Joel Coehoorn