Comma separated lists in java
I find myself doing this for a user a million times and have taken until now to take care of the formatting somewhere else. If you need a list that has commas in between items, but of course doesn't have a trailing comma, something like this is handy:
/**
* bch: formats a comma-separated list
* @param items string separated by spaces
* @return list in format a, b, c
*/
public static String commalist(String items) {
StringTokenizer st = new StringTokenizer(items);
StringBuffer sb = new StringBuffer();
while (st.hasMoreElements()) {
sb.append(st.nextToken());
if (st.hasMoreElements()) {
sb.append(", ");
}
}
return sb.toString();
}


1 Comments:
Hi,
Useful article. Very well explained. Thanks for sharing.
Cheers,
http://www.flowerbrackets.com/java-if-else/
Post a Comment
<< Home