Question

Or a better way than this?

String concat(String[] strings) {
  StringBuilder out = new StringBuilder();

  for(String next: strings) {
    out.append(next);
  }

  return out.toString();
}

No worries if no, I just feel like there should be a built in?

Was it helpful?

Solution

No, not in the current Java library.

In JDK7 you should be able to write String.join("", strings). It was found that "85%" of the uses for wanting an index in the posh for loop was to do a string join (which you can do without anyway).

I guess if you want to be uber efficient, you could write it as something like:

public static String concat(String... strs) {
    int size = 0;
    for (String str : strs) {
        size += str.length;
    }

    final char[] cs = new char[size];
    int off = 0;
    try {
        for (String str : strs) {
            int len = str.length();
            str.getChars(0, len, cs, off);
            off += len;
        }
    } catch (ArrayIndexOutOfBoundsException exc) {
        throw new ConcurrentModificationException(exc);
    }
    if (off != cs.length) {
        throw new ConcurrentModificationException();
    }
    return new String(cs);
}

(Not compiled or tested, of course.)

OTHER TIPS

Take a look at the new Google Guava libraries, which will incorporate Google Collections once it passes from 1.0RC4 to 1.0. Guava and Collections give you quite a bit of power and elegance, and are already used extensively in Google production code.

The Joiner class suits your example perfectly:

String[] strings = { "Stack", "Overflow", ".com" };
String site = Joiner.on("").join(strings);

Aleksander Stensby has a nice four part exploration of Guava/Collections.

Like Apache Collections, it's not part of the JDK, though it builds very carefully on top of java.util.collection.

org.apache.commons.lang.StringUtils.join

Second recommendation to look at Google Guava.

The Google Collections was released last week, and this week, Guava has been released for testing. The Google Collections stuff is solid and the API will not change. I much prefer Google Collections over the apache one, specifically because its fully generic. The Google folks also claim that its fast enough for them to use in production, which is fairly impressive, altho I can't verify that personally.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top