Если для вас важнее отсутствие цикла, чем предотвращение импорта другой библиотеки, или если вы уже используете apache commons lang , в любом случае, вы можете использовать StringUtils.join method
import org.apache.commons.lang.StringUtils;
String joined = StringUtils.join(s, "");
Возможно, у Apache Commons есть другие методы, которые также могут быть интересны для вашего проекта. Я обнаружил, что они являются очень полезным ресурсом для недостающих функций в собственных библиотеках Java.
Without looping, you can:
public String joinpart(String[] a, int i, String prefix) {
if (i < a.length) {
return joinpart(a, i + 1, prefix + a[i]);
}
return prefix;
}
then:
String[] a = new String[]{"Ap", "p", "le"};
String apple = joinpart(a, 0, "");
This is called a recursive solution.
If you know the length of your array, you can easily do the following:
String result = s[0] + s[1] +s[2];
Another option is to do the following, (which is purely academic, I would not use it in a real-world scenario as it would remove [
, ]
, and
from your strings):
String result = Arrays.toString(s).replaceAll("[\\]\\[, ]", "");
Yet another option, to go along with the first attempt, but using a C-like formatter:
System.out.println(String.format("%s%s%s", s));
String result = s[0] + s[1] + s[2];
If you have an unknown number of entries, I think you'll need a loop.
В Java нет метода типа String.join ()
. Если вы хотите скрыть петлю, вам придется свернуть одну.
используя Доллар просто набрать:
String[] array = new String[] { "Ap", "p", "le" };
String result = $(array).join(); // result now is "Apple"