gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 09:42:40 25 4
gpt4 key购买 nike

或者比这更好的方法?

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

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

return out.toString();
}

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

最佳答案

不,不在当前的 Java 库中。

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

我想如果你想变得 super 高效,你可以这样写:

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);
}

(当然没有编译或测试。)

关于Java - 是否有用于连接 String[] 中的字符串的内置函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1810954/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com