This is a common scenario. I will simplify it a little to illustrate some solutions:
Option # 1 - delete the last character by changing the length of the StringBuffer:
StringBuffer sb = new StringBuffer(); Enumeration en = ... while (en.hasMoreElements()) sb.append(en.nextElement()); sb.append(","); } if (sb.length() > 0) { sb.setLength(sb.length() - 1); } System.err.println(sb.toString());
Option number 2 - add a separator if the buffer is not empty.
StringBuffer sb = new StringBuffer(); Enumeration en = ... while (en.hasMoreElements()) if (sb.length() > 0) { sb.append(","); } sb.append(en.nextElement()); } System.err.println(sb.toString());
Option number 3 - add a separator if there are more elements ...
StringBuffer sb = new StringBuffer(); Enumeration en = ... while (en.hasMoreElements()) sb.append(en.nextElement()); if (en.hasMoreElements()) { sb.append(","); } } System.err.println(sb.toString());
Option number 4 - add a separator, if this is not the first time around the loop ...
StringBuffer sb = new StringBuffer(); Enumeration en = ... boolean first = true; while (en.hasMoreElements()) if (first) { first = false; } else { sb.append(","); } sb.append(en.nextElement()); } System.err.println(sb.toString());
Which best depends on accurate data about what you are doing and how important performance is.
Lastly, I should point out that you need to be more careful when compiling URLs in general and query strings. For example, you need to correctly avoid any characters that are not "unconditional" (according to the specification of the URL) in the names and values ββof parameters. If you are careless, you may have a vector for injecting XSS attacks on your site.
source share