Re: Composing Strings

May 3rd, 2003

I got a nice reaction on Composing Strings, from somebody who apparently wants to remain anonymous:

StringBuffer sb = new StringBuffer();
for (Iterator it = list.iterator(); it.hasNext(); sb.append(it.hasNext()?"and":"")) {
sb.append(it.next().toString());
}
This answers all the criteria of the problem. Alas, readability wasn't one of them (as noted by himself, BTW).

So does atog's solution, which is more readable, but I still feel it as a waste of energy to add things, and then take them away again. Maybe I'm just being stubborn on this.

And no, Java has no String.join() operation as one kind soul suggested in the comments. Looks like something for Yet Another Util Package.

1 Response to “Re: Composing Strings”

  1. Gregg Says:
    Why not use the apache jakarta project's Commons Lang package? http://jakarta.apache.org/commons/lang.html It has a StringUtils package with two join methods that fit the bill, as well as a lot of other useful functions.

Leave a Reply