I often use this piece of code in PHP
$ordine[\'address\'] = implode(\', \', array_filter(array($cliente[\'cap\'], $cliente[\'citta\'], $cliente[\'provincia\'
Here's my implode implementation:
/**
* Implodes the specified items, gluing them using the specified glue replacing nulls with the specified
* null placeholder.
* @param glue The text to use between the specified items.
* @param nullPlaceholder The placeholder to use for items that are <code>null</code> value.
* @param items The items to implode.
* @return A <code>String</code> containing the items in their order, separated by the specified glue.
*/
public static final String implode(String glue, String nullPlaceholder, String ... items) {
StringBuilder sb = new StringBuilder();
for (String item : items) {
if (item != null) {
sb.append(item);
} else {
sb.append(nullPlaceholder);
}
sb.append(glue);
}
return sb.delete(sb.length() - glue.length(), sb.length()).toString();
}
Use this simple function:
private String my_implode(String spacer, String[] in_array){
String res = "";
for (int i = 0 ; i < in_array.length ; i++) {
if (!res.equals("")) {
res += spacer;
}
res += in_array[i];
}
return res;
}
Use:
data_arr = {"d1", "d2", "d3"};
your_imploded_text = my_implode(",", data_arr);
// Output: your_imploded_text = "d1,d2,d3"
You'd have to add your strings to an ArrayList, remove empty ones, and format it accordingly:
public static String createAddressString( String street, String zip_code, String country) {
List<String> list = new ArrayList<String>();
list.add( street);
list.add( zip_code);
list.add( country);
// Remove all empty values
list.removeAll(Arrays.asList("", null));
// If this list is empty, it only contained blank values
if( list.isEmpty()) {
return "";
}
// Format the ArrayList as a string, similar to implode
StringBuilder builder = new StringBuilder();
builder.append( list.remove(0));
for( String s : list) {
builder.append( ", ");
builder.append( s);
}
return builder.toString();
}
Additionally, if you had String[]
, an array of strings, you can easily add them to an ArrayList:
String[] s;
List<String> list = new ArrayList<String>( Arrays.asList( s));
public static String implode(List<String> items, String separator) {
if (items == null || items.isEmpty()) {
return null;
}
String delimiter = "";
StringBuilder builder = new StringBuilder();
for (String item : items) {
builder.append(delimiter).append(item);
delimiter = separator;
}
return builder.toString();
}
Why so serious?
Try StringUtils.join(new String[] {"Hello", "World", "!"}, ", ")
!
Here is an Android-specific answer that may be helpful to some:
String combined = TextUtils.join(",", new String[]{"Red", "Green", "Blue"});
// Result => Red,Green,Blue
Be sure to import the TextUtils class:
import android.text.TextUtils;