Remove Trailing Zeros From String in Java

Given a string of digits, remove trailing zeros from it.


Input : 00000123569
Output : 123569

Input : 000012356090
Output : 12356090

We use StringBuffer class as Strings are immutable.

1) Count trailing zeros.
2) Use StringBuffer replace function to remove characters equal to above count.

// Java program to remove trailing/preceding zeros
// from a given string
import java.util.Arrays;
import java.util.List;

/* Name of the class to remove trailing/preceding zeros */
class RemoveZero
    public static String removeZero(String str)
        // Count trailing zeros
        int i = 0;
        while (str.charAt(i) == '0')

        // Convert str into StringBuffer as Strings
        // are immutable.
        StringBuffer sb = new StringBuffer(str);

        // The  StringBuffer replace function removes
        // i characters from given index (0 here)
        sb.replace(0, i, "");

        return sb.toString();  // return in String

    // Driver code
    public static void main (String[] args)
        String str = "00000123569";
        str = removeZero(str);



Remove Trailing Zeros From string in C++

This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Please write to us at to report any issue with the above content.

Recommended Posts:

2.5 Average Difficulty : 2.5/5.0
Based on 6 vote(s)