Remove last character of a StringBuilder? Remove last character of a StringBuilder? java java

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.


Another simple solution is:

sb.setLength(sb.length() - 1);

A more complicated solution:

The above solution assumes that sb.length() > 0 ... i.e. there is a "last character" to remove. If you can't make that assumption, and/or you can't deal with the exception that would ensue if the assumption is incorrect, then check the StringBuilder's length first; e.g.

// Readable versionif (sb.length() > 0) {   sb.setLength(sb.length() - 1);}

or

// Concise but harder-to-read version of the above.sb.setLength(Math.max(sb.length() - 1, 0));


if(sb.length() > 0){    sb.deleteCharAt(sb.length() - 1);}