HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaCritical

Remove last character of a StringBuilder?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
lastcharacterremovestringbuilder

Problem

When you have to loop through a collection and make a string of each data separated by a delimiter, you always end up with an extra delimiter at the end, e.g.

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


Gives something like : serverId_1, serverId_2, serverId_3,

I would like to delete the last character in the StringBuilder (without converting it because I still need it after this loop).

Solution

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.

Code Snippets

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

Context

Stack Overflow Q#3395286, score: 751

Revisions (0)

No revisions yet.