Remove last character of a StringBuilder?

To remove the last character of a StringBuilder in Java, you can use the deleteCharAt method and pass in the index of the character you want to delete.

Here is an example of how you can use the deleteCharAt method:

StringBuilder sb = new StringBuilder("Hello, world!");
int len = sb.length();
if (len > 0) {
  sb.deleteCharAt(len - 1);
}
System.out.println(sb);  // Outputs "Hello, worl"

This code gets the length of the StringBuilder and then uses the deleteCharAt method to remove the last character if the length is greater than 0.

You can also use the setLength method to truncate the StringBuilder to a specific length. For example, to remove the last two characters, you could use the following code:

StringBuilder sb = new StringBuilder("Hello, world!");
int len = sb.length();
if (len > 2) {
  sb.setLength(len - 2);
}
System.out.println(sb);  // Outputs "Hello, wor"

I hope this helps! Let me know if you have any other questions.