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!
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.
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”).
The AppendLine() method appends the content and add a new line on the end.
Well, the backslash (“\”) in the new line character is called an escape sequence. Escape sequences are used to add anything illegal to a string.
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()); }
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"; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With