Java - 是否有用于在String []中连接字符串的内置函数?
题
还是比这更好的方式?
String concat(String[] strings) {
StringBuilder out = new StringBuilder();
for(String next: strings) {
out.append(next);
}
return out.toString();
}
不用担心,如果不是,我觉得应该有一个内置的?
解决方案
不,不在当前的Java库中。
在JDK7中,您应该能够编写 String.join("",strings)
。发现“85%”是指“85%”。想要在posh for循环中使用索引的用法是进行字符串连接(无论如何都可以这样做)。
我想如果你想要有效率,你可以把它写成:
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);
}
(当然没有编译或测试过。)
其他提示
查看新的 Google Guava图书馆,其中包含 Google Collections 从1.0RC4传递到1.0。 Guava和Collections为您提供了相当多的力量和优雅,并已广泛用于Google生产代码。
Joiner class完全适合你的例子:
String[] strings = { "Stack", "Overflow", ".com" };
String site = Joiner.on("").join(strings);
Aleksander Stensby对番石榴/收藏品进行了很好的四部分探索。
与Apache Collections一样,它不是JDK的一部分,尽管它在java.util.collection之上非常仔细地构建。
org.apache.commons.lang.StringUtils.join
关于Google Guava的第二个建议。
Google Collections上周发布,本周,Guava已经发布用于测试。 Google Collections的内容非常可靠,API也不会改变。我非常喜欢Google Collections而非apache one,特别是因为它完全通用。谷歌人还声称它的速度足以让他们在制作中使用,这相当令人印象深刻,但我无法亲自验证。
不隶属于 StackOverflow