Java function for arrays like PHP's join()?
I want to join a String[]
with a glue string. Is there a function for this?
Solution 1:
Starting from Java8 it is possible to use String.join()
.
String.join(", ", new String[]{"Hello", "World", "!"})
Generates:
Hello, World, !
Otherwise, Apache Commons Lang has a StringUtils
class which has a join
function which will join arrays together to make a String
.
For example:
StringUtils.join(new String[] {"Hello", "World", "!"}, ", ")
Generates the following String
:
Hello, World, !
Solution 2:
If you were looking for what to use in android, it is:
String android.text.TextUtils.join(CharSequence delimiter, Object[] tokens)
for example:
String joined = TextUtils.join(";", MyStringArray);
Solution 3:
In Java 8 you can use
1) Stream API :
String[] a = new String[] {"a", "b", "c"};
String result = Arrays.stream(a).collect(Collectors.joining(", "));
2) new String.join method: https://stackoverflow.com/a/21756398/466677
3) java.util.StringJoiner class: http://docs.oracle.com/javase/8/docs/api/java/util/StringJoiner.html
Solution 4:
You could easily write such a function in about ten lines of code:
String combine(String[] s, String glue)
{
int k = s.length;
if ( k == 0 )
{
return null;
}
StringBuilder out = new StringBuilder();
out.append( s[0] );
for ( int x=1; x < k; ++x )
{
out.append(glue).append(s[x]);
}
return out.toString();
}