Home Page

Tips page

University Page

Programming

Debian & Linux

Some works

About me

Del.icio.us Bookmarks

BOINC Combined Statistics

Site Statistics

Contact me sending an e-mail (antispam defense activated)

debian

hacker emblem

blogger

GeoURL

View Sandro Tosi's profile on LinkedIn

This is my Google PageRank

Separate Items the Right Way

Separate Items the Right Way

 Sandro Tosi, 16 May 2007


You have an array of items you have to separate (typically) with a comma. There are some solutions to this, but only one is the right one...

The Java code provided shows three ways to separate array items, and the last one is what you'd like to have: at the beginning, the separator string is empty, after the first cycle, it contains the right separator.

Here is class code (highlighted with java2html), the full source code is available at this link:

public class separation {
public static String separateCommaFirst(String[] input) {
String separator = ", ";
StringBuffer output = new StringBuffer();
for (int i=0; i<input.length; i++) {
output.append(separator).append(input[i]);
}
return output.toString();
}

public static String separateCommaLast(String[] input) {
String separator = ", ";
StringBuffer output = new StringBuffer();
for (int i=0; i<input.length; i++) {
output.append(input[i]).append(separator);
}
return output.toString();
}

public static String separateRightWay(String[] input)
{
String separator = "";
StringBuffer output = new StringBuffer();
for (int i=0; i<input.length; i++) {
output.append(separator).append(input[i]);
separator = ", ";
}
return output.toString();
}

public static void main(String[] args)
{
String[] arrayToSeparate = {"this", "has", "to", "be", "comma", "separated", "in", "a", "beauty", "way"};
System.out.println("Output of separateCommaFirst: >"+separateCommaFirst(arrayToSeparate)+"<");
System.out.println("Output of separateCommaLast: >"+separateCommaLast(arrayToSeparate)+"<");
System.out.println("Output of separateGoodWay: >"+separateRightWay(arrayToSeparate)+"<");
}
}

The output is of this class is this (between minor/major characters): 

$ javac separation.java && java separation
Output of separateCommaFirst: >, this, has, to, be, comma, separated, in, a, beauty, way<
Output of separateCommaLast: >this, has, to, be, comma, separated, in, a, beauty, way, <
Output of separateGoodWay: >this, has, to, be, comma, separated, in, a, beauty, way<

Drop me an email, if you'd like to provide some comments.