Languages
[Edit]
EN

Java - remove last n characters from string

0 points
Created by:
Callen-Payne
384

In this article, we would like to show you how to remove the last n characters from the string in Java.

Quick solution:

String text = "ABCD";
int n = 3;
String result = text.substring(0, text.length() - n);

System.out.println(result);  // A

 

Practical examples

1. Using String substring() method

In this example, we use String substring() method to create a new result substring from the text string without the last n = 3 characters.

Syntax:

substring(int startIndex, int endIndex);

Practical example:

public class Example {

    public static void main(String[] args) {
        String text = "ABCD";
        int n = 3;
        String result = text.substring(0, text.length() - n);

        System.out.println(result);  // A
    }
}

Output:

A

2. Using StringBuilder delete() method

In this example, we create sb StringBuilder object from the text string, then we use delete() method on the sb to delete the last n = 3 characters. 

Syntax:

delete(int startIndex, int endIndex);

Practical example:

public class Example {

    public static void main(String[] args) {
        String text = "ABCD";
        int n = 3;

        // Create StringBuilder object
        StringBuilder sb = new StringBuilder(text);

        // Remove last n = 3 characters
        sb.delete(text.length() - n, text.length());

        System.out.println(sb);  // A
    }
}

Output:

A

3. Using StringBuffer delete() method 

In this example, we create sb StringBuffer object from the text string, then we use delete() method on the sb to delete the last n = 3  characters. 

Syntax:

delete(int startIndex, int endIndex);

Practical example:

public class Example {

    public static void main(String[] args) {
        String text = "ABCD";
        int n = 3;

        // Create StringBuffer object
        StringBuffer sb = new StringBuffer(text);

        // Remove last n = 3 characters
        sb.delete(text.length() - n, text.length());

        System.out.println(sb);  // A
    }
}

Output:

A

Java - String (popular problems)

Java - remove last n characters from string
Native Advertising
ūüöÄ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

‚̧ԳŹūüíĽ ūüôā

Join