Write code to Join 0..n strings separated by a delimiter.
//package com.book2s; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; import java.util.Iterator; public class Main { public static void main(String[] argv) { String delimiter = "book2s.com"; Iterator iterator = java.util.Arrays.asList("asdf", "book2s.com") .iterator();//w w w . j av a 2 s . co m System.out.println(join(delimiter, iterator)); } public static String join(final String delimiter, final Iterator<?> iterator) { if (iterator == null) { return null; } final StringBuilder sb = new StringBuilder(); while (iterator.hasNext()) { sb.append(iterator.next().toString()); sb.append(delimiter); } // remove last delimiter final int bufLen = sb.length(); if (bufLen > 0) { // only removed if we ever added anything sb.delete(bufLen - delimiter.length(), bufLen); } return sb.toString(); } public static String join(final String delimiter, final String... strings) { if (strings == null) { return null; } if (strings.length == 0) { return ""; } final StringBuilder sb = new StringBuilder(); // add first 1.. n-1 final int len = strings.length - 1; int i = 0; for (; i < len; i++) { sb.append(strings[i]); sb.append(delimiter); } // add last sb.append(strings[i]); return sb.toString(); } public static String toString(final Throwable throwable) { final Writer result = new StringWriter(); final PrintWriter printWriter = new PrintWriter(result); throwable.printStackTrace(printWriter); return result.toString(); } }