Java - 是否有用于在String []中连接字符串的内置函数?

gav*_*gav 1 java string concat

还是比这更好的方式?

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

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

  return out.toString();
}
Run Code Online (Sandbox Code Playgroud)

不用担心,如果没有,我觉得应该有一个内置?

Tom*_*ine 6

不,不在当前的Java库中.

在JDK7中你应该能够写String.join("", strings).结果发现,在posh for循环中需要索引的"85%"用法是进行字符串连接(无论如何你都可以这样做).

我想如果你想要超高效,你可以把它写成:

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);
}
Run Code Online (Sandbox Code Playgroud)

(当然没有编译或测试过.)


Jim*_*ans 5

看看新的Google Guava库,一旦从1.0RC4传递到1.0 ,它将包含Google Collections.Guava和Collections为您提供了相当多的力量和优雅,并且已经在Google生产代码中广泛使用.

类适合您的完美例子:

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

亚历山大·斯坦斯比(Aleksander Stensby)对番石榴/收藏品进行了很好的四部分探索.

与Apache Collections一样,它不是JDK的一部分,尽管它在java.util.collection之上非常仔细地构建.