Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove last character of a StringBuilder?

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).

like image 223
Matthew Avatar asked Aug 03 '10 09:08

Matthew


People also ask

How do I remove the last character of a StringBuilder?

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.

How do I remove a character from StringBuilder?

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.

How do I remove the last two characters in string builder?

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.

How do I remove the last character of a line?

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.


2 Answers

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.

like image 119
Jon Skeet Avatar answered Sep 19 '22 08:09

Jon Skeet


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)); 
like image 30
Stephen C Avatar answered Sep 22 '22 08:09

Stephen C