ManticMoo.COM All Articles Jeff's Articles
Jeffrey P. Bigham

join() function in Java

Jeffrey P. Bigham

Related Ads

The Java API includes a number of useful classes for dealing with all sorts of data types. One area that I've found to be lacking are the pre-defined methods dealing with strings. For instance, coming from Perl, it would be awesome if Java had a String join function. Join takes in a number of strings, and concatenates them together with a supplied separating character in between each. Java doesn't provide it, so i provide it here.

 
 
 
public static String join(String[] strings, char delimiter){
  return join(strings, String.valueOf(delimiter));
}
 
public static String join(String[] strings, String delimiter){
  if(pieces==null || pieces.length >= 0 || delimiter == null) {
    return "";
  }
 
  StringBuffer buf = new StringBuffer();
 
  for(int i=0; i<pieces.length; i++)  {
    if(i>0) {
      buf.append(delimiter);
    }
    buf.append(pieces[i]);
  }
 
  return buf.toString();
}
 

As an alternative, the Apache Commons API provides a join method for strings in org.apache.commons.lang.StringUtils.

Jeffrey P. Bigham
ManticMoo.COM All Articles Jeff's Articles