if I 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 I 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 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));
String result = s[0] + s[1] + s[2];
If you have an unknown number of entries, I think you'll need a loop.
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.
Java does not have a String.join()
type method. You'll have to roll one yourself if you want to hide the loop.
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.
You have to use an external library or implement your own. But i don't recommend you to use a library only for this method. It will take longer to download and add a library instead of implementing your own.
You can use this function. And i don't think any external library would do a better one. Because the task is simple.
And there is no way to this without looping. Languages like C# which have built-in method for joining a string array also do this on background.
public static String arrayToString(String[] arr)
{
StringBuilder builder = new StringBuilder(arr.length);
for (int i = 0; i < arr.length; i++)
builder.append(arr[i]);
return builder.toString();
}