Java equivalent to Explode and Implode(PHP)

Pankaj Wanjari picture Pankaj Wanjari · May 27, 2013 · Viewed 128.5k times · Source

I am new in Java although had a good experience in PHP, and looking for perfect replacement for explode and implode (available in PHP) functions in Java.

I have Googled for the same but not satisfied with the results. Anyone has the good solution for my problem will be appreciated.

For example:

String s = "x,y,z";
//Here I need a function to divide the string into an array based on a character.
array a = javaExplode(',', s);  //What is javaExplode?
System.out.println(Arrays.toString(a));

Desired output:

[x, y, z]

Answer

Brian Roach picture Brian Roach · May 27, 2013

The Javadoc for String reveals that String.split() is what you're looking for in regard to explode.

Java does not include a "implode" of "join" equivalent. Rather than including a giant external dependency for a simple function as the other answers suggest, you may just want to write a couple lines of code. There's a number of ways to accomplish that; using a StringBuilder is one:

String foo = "This,that,other";
String[] split = foo.split(",");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < split.length; i++) {
    sb.append(split[i]);
    if (i != split.length - 1) {
        sb.append(" ");
    }
}
String joined = sb.toString();