StringBuilder builder = new StringBuilder();
string newline = "";
foreach (Map.Entry<MyClass.Key,String> entry : data.entrySet())
{
builder.append(newline)
.append(entry.key())
.append(": ")
.append(entry.value());
newline = "\n";
}6 posts tagged “stackoverflow”
It's been a while since I've posted here, so to get caught up here a few of my own posts from StackOverflow that I'm most proud of:
Follow up to this post.
public static string JoinWith(this IEnumerable<string> strings, string separator)
{
return String.Join(separator, strings.ToArray());
}Most .Net programmers who need to use JSON can either pull in a third-party library or are using .Net 3.5 and therefore can rely on the built-in JavascriptSerializer . However, I recently found myself needing to turn a .Net DataTable into JavaScript Object Notation without either of those options available.
My first thought was that something must already be out there that I could use. Indeed, there are some really great libraries for this. Unfortunately, my situation is such that I can't pull in a whole library. I needed some purpose-specific code. I did find some specific implementations as well, but I found them all some how lacking and ended up rolling my own. The code itself would take up about 2 printed pages, so I'll content myself with posting the link for now.
Today's question: How do I append a newline character for all lines except the last one?
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());
}This is something I stumbled on a while ago and known how to do in a basic sense. But now thanks to this StackOverflow question I also know what it's called. This will make a huge impact on my ability to use this in the future, as before I couldn't really search google or msdn to get help with it.
Today I came across a question about virtualizing web servers and databases. It caught my eye because I'd asked a similar question back in November.