Converting arrays to/from strings

Found myself using these functions in various prints to interfaces and whatnot, so here’s the elegant ways of creating comma-separated strings. The added bonus is that this method allows for separation of data in for-loops. Early on I’d usually add a separation manually in each step of the loop and finish by removing the extra separation at the end.

Python:

string = ",".join(['1','2','3','4'])
array = string.split(",")

PHP:

echo($str = implode(",", [1,2,3,4,5]));
var_dump(explode(",",$str));

Java:

With Apache Commons:

StringUtils.join(new String[]{"1","2","3"}, ',');

In Android:

TextUtils.join(new String[]{"1","2","3"}, ',');

Without requires a bit of setup with StringBuilder and a for-loop, unless you use JDK8:

String[] array = {"1", "2", "3", "4", "5"};
System.out.println(String.join(",",array));

Check out the new StringJoiner class for some interesting helper functions.

Leave a Reply

Your email address will not be published. Required fields are marked *