Remove last character of a StringBuilder?

Others have pointed out the deleteCharAt method, but here’s another alternative approach:

String prefix = "";
for (String serverId : serverIds) {
  sb.append(prefix);
  prefix = ",";
  sb.append(serverId);
}

Alternatively, use the Joiner class from Guava đź™‚

As of Java 8, StringJoiner is part of the standard JRE.

Leave a Comment