Composing Strings
April 22nd, 2003
An entirely non-issue, but I'm curious nevertheless: What do you, Java programmer, use to create sentences while looping through a list? Often, you have to generate some String based on the contents of some Iterator (to generate output, or an error message, or whatever). In most cases, this asks for some kind of separator, which should be between two elements, but not in the beginning nor the end of the resulting String.
The construct I like most till now, is
StringBuffer sb = new StringBuffer();
String and = "";
for (Iterator iter = myList.iterator(); iter.hasNext();) {
sb.append(and);
sb.append(iter.next().toString());
and = " and ";
}
I've also seen boolean to keep track of whether you're handling the first element or not, and I've seen StringBuffers loosing their tails after the loop... The above is quite nice, but the scope of the and String is too large.
Anyway, consider this an exchange of taste: what construct do you usually use to achieve this?

April 21st, 2008 at 10:16 PM Doesn't Java have String.join? (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemstringclassjointopic.asp)
April 21st, 2008 at 10:16 PM Re: Composing Strings I got a nice reaction on Composing Strings, from somebody who apparently wants to remain anonymous: StringBuffer sb = new...