基本上,我得到了这个:
(path
是一个字符串数组)
String writer = "";
for (int i = 0; i < path.length; i++) {
writer += path[i] + "{";
}
writer += string;
for (int i = 0; i < path.length; i++) {
writer += "}";
}
但这看起来很丑陋而效率低下。有没有办法将它正确地组合成一个for-loop?
答案 0 :(得分:5)
这是一个没有for
- 循环且使用StringBuilder
而不是+=
的解决方案 - 可能导致内存和性能问题的构造。
StringBuilder firstPart = new StringBuilder();
StringBuilder lastPart = new StringBuilder();
Arrays.stream(path)
.forEach(elem -> {
firstPart.append(elem);
firstPart.append("{");
lastPart.append("}");
});
firstPart.append(string);
firstPart.append(lastPart.toString());
String writer = firstPart.toString();
答案 1 :(得分:3)
没有智能手段,以下速度更快:
StringBuilder sb = new StringBuilder();
for (String p : path) { // Might cost a bit of speed.
sb.append(p).append('{');
}
sb.append(string);
for (int i = 0; i < path.length; ++i) {
sb.append('}');
}
String writer = sb.toString();
在一个循环中:
StringBuilder sb = new StringBuilder(string);
for (int i = path.length - 1; i >= 0; --i) {
sb.insert(0, '{');
sb.insert(0, path[i]);
sb.append('}');
}
String writer = sb.toString();