java string explode and implode

Some nice java function to explode string into array or implode array into string as equivalent to PHP implode and explode function.

Explode

Convert string to array of tokens.

Function #1 – Explode using org.apache.commons.lang.StringUtils

import org.apache.commons.lang3.StringUtils;

...

//explode function #1
//using org.apache.commons.lang package
//api and jar download available @ http://commons.apache.org/
public static String[] explodeStringUsingStringUtils(String stringToExplode,String separator){
	return  StringUtils.splitPreserveAllTokens(stringToExplode, separator);
}

...
//usage
String stringToExplode = "apple,pear,banana,,durian";
String separator = ",";
String[] arrExploded = explodeStringUsingStringUtils(stringToExplode,separator);

/*
 * String[] arrExploded will contain
 * 0 - "apple"
 * 1 - "pear"
 * 2 - "banana"
 * 3 - ""
 * 4 - "durian" 
 */

Function #2 – Explode using core java.lang

//explode function #2
//using core java lang
public static String[] explodeStringUsingCoreJava(String stringToExplode,String separator){		
	return  stringToExplode.split(separator);
}

...

//usage
String stringToExplode = "apple,pear,banana,,durian";
String separator = ",";
String[] arrExploded = explodeStringUsingCoreJava(stringToExplode,separator);

/*
 * String[] arrExploded will contain
 * 0 - "apple"
 * 1 - "pear"
 * 2 - "banana"
 * 3 - ""
 * 4 - "durian" 
 */

Implode

Concatenate/merge array of string into a single continuous string.

Function #1 – Implode using org.apache.commons.lang.StringUtils

import org.apache.commons.lang3.StringUtils;

...

//implode function #1
//using org.apache.commons.lang package
//api and jar download available @ http://commons.apache.org/
public static String implodeArrayUsingStringUtils(String[] arrayToImplode,String separator){
	return StringUtils.join(arrayToImplode, separator);
}

...

//usage
String[] arrExploded = {"Denny","de","Web","Monster"};
String implodeString = implodeArrayUsingStringUtils(arrExploded,"+");

/*
 * String implodeString will contain 
 * "Denny+de+Web+Monster"
 */		

Function #2 – Implode using for loop

//implode function #2
//using for loop	
public static String implodeArrayUsingForLoop(String[] arrayToImplode,String separator){		

	if (arrayToImplode.length == 0) {
		//empty array return empty string 
		return "";
	}
	
	if(arrayToImplode.length < 2){
		//only 1 item
		return arrayToImplode[0];
	}
	
	StringBuffer stringbuffer = new StringBuffer();
    for (int i=0; i < arrayToImplode.length; i++) {
        if (i != 0) stringbuffer.append(separator);
        stringbuffer.append(arrayToImplode[i]);
  	}
    
    //return the implode string
  	return stringbuffer.toString();	
}

...

//usage
String[] arrExploded = {"Denny","de","Web","Monster"};
String implodeString = implodeArrayUsingForLoop(arrExploded,"-");
	

/*
 * String implodeString will contain 
 * "Denny-de-Web-Monster"
 */

That’s all folks. Have fun.