gav
gav

Reputation: 29122

Java - is there an built in function for concatenating the Strings in a String[]?

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?

Upvotes: 1

Views: 1609

Answers (4)

fishtoprecords
fishtoprecords

Reputation: 2404

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.

Upvotes: 0

Jim Ferrans
Jim Ferrans

Reputation: 31012

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.

Upvotes: 5

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147154

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.)

Upvotes: 6

Anton Kuzmin
Anton Kuzmin

Reputation: 831

org.apache.commons.lang.StringUtils.join

Upvotes: 2

Related Questions