Getting all the values of an array of Strings in one String
if 开发者_如何学JAVAI have,
String[] s = new String[3];
s[0] = "Ap";
s[1] = "p";
s[2] = "le";
String result = ?
If I want to get Apple out of s without looping, how do I do that?
Any short cut?
If the not looping is more important to you than preventing to import another library or if you are using apache commons lang already, anyway, you can use the StringUtils.join method
import org.apache.commons.lang.StringUtils;
String joined = StringUtils.join(s, "");
Maybe the Apache Commons have other methods that might be interesting for your project, as well. I found them to be a very useful resource for missing features in the native Java libraries.
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 <space>
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));
using Dollar is simple as typing:
String[] array = new String[] { "Ap", "p", "le" };
String result = $(array).join(); // result now is "Apple"
String result = s[0] + s[1] + s[2];
If you have an unknown number of entries, I think you'll need a loop.
Java does not have a String.join()
type method. You'll have to roll one yourself if you want to hide the loop.
精彩评论