Languages
[Edit]
EN

Java - Remove last character from string builder in java

9 points
Created by:
AnnLen
1777

Remove last character from StringBuilder in Java is simple. StringBuilder has build in method deleteCharAt(). As a parameter we pass current length of our StringBuilder.

Syntax:

StringBuilder builder = new StringBuilder();

builder.deleteCharAt( builder.length() - 1 );

1. Remove last char

public class Example {

    public static void main(String[] args) {

        StringBuilder builder = new StringBuilder();

        builder.append("1234");
        System.out.println( builder.toString() ); // 1234

        builder.deleteCharAt( builder.length() - 1 );
        System.out.println( builder.toString() ); // 123
    }
}

2. Safe way to remove last char

In order to saftly remove last character from StringBuilder in java, we need to check the length of StringBuilder. In case we won't do it and the StringBuilder will be longer we get:

java.lang.StringIndexOutOfBoundsException

Example with safe way of how to remove last char:

public class Example {

    public static void main(String[] args) {

        StringBuilder builder = new StringBuilder();

        builder.append("1234");
        System.out.println( builder.toString() ); // 1234

        removeLastChar(builder);
        System.out.println( builder.toString() ); // 123
    }

    public static void removeLastChar(StringBuilder builder) {
        if (builder.length() > 0) {
            builder.deleteCharAt( builder.length() - 1 );
        }
    }
}

This method allow us to avoid the below exception:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: 
String index out of range: -1
	at java.lang.AbstractStringBuilder.deleteCharAt(AbstractStringBuilder.java:824)
	at java.lang.StringBuilder.deleteCharAt(StringBuilder.java:253)

3. Remove last char if it is equal to specific character

This example extends the previous one. We just add one more condition. We need to check if the last letter of StringBuilder is equals to the letter we want to find.

public class Example {

    public static void main(String[] args) {

        StringBuilder builder = new StringBuilder();

        builder.append("1234a");
        System.out.println( builder.toString() ); // 1234a

        removeLastChar(builder, 'a');
        System.out.println( builder.toString() ); // 1234
    }

    public static void removeLastChar(StringBuilder builder, char letter) {
        if (builder.length() > 0 && builder.charAt(builder.length() - 1) == letter) {
            builder.deleteCharAt(builder.length() - 1);
        }
    }
}

References

  1. StringBuilder - oracle docs
Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.