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).
The idea is to use the deleteCharAt() method of StringBuilder class to remove first and the last character of a string. The deleteCharAt() method accepts a parameter as an index of the character you want to remove. Remove last character of a string using sb. deleteCharAt(str.
In order to remove a substring from a Java StringBuilder Object, we use the delete() method. The delete() method removes characters in a range from the sequence. The delete() method has two parameters, start, and end. Characters are removed from start to end-1 index.
Using StringBuilder's deleteCharAt() Method It allows us to remove the character at the desired position. The deleteCharAt() method has only one argument: the char index we want to delete. Therefore, if we pass the last character's index to the method, we can remove the character.
In order to remove the last character of a given String, we have to use two parameters: 0 as the starting index, and the index of the penultimate character. We can achieve that by calling String's length() method, and subtracting 1 from the result.
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 version if (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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With