Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Remove Leading Zeros From String in Java

  • Difficulty Level : Easy
  • Last Updated : 02 May, 2022

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


Input  : 00000123569
Output : 123569
Input  : 000012356090
Output : 12356090

Approach: We use the StringBuffer class as Strings are immutable.

  • Count leading zeros by iterating string using charAt(i) and checking for 0 at the “i” th indices.
  • Converting a string into StringBuffer object as strings are immutable
  • Use StringBuffer replace function to remove characters equal to the above count using replace() method.
  • Returning string after removing zeros



// Java program to Remove leading/preceding
// zeros from a given String
// Importing required classes
import java.util.Arrays;
import java.util.List;
// Main class
// RemoveZero
class GFG {
    // Method 1
    // to Remove leading zeros in a string
    public static String removeZero(String str)
        // Count leading zeros
        // Initially setting loop counter to 0
        int i = 0;
        while (i < str.length() && str.charAt(i) == '0')
        // Converting string into StringBuffer object
        // 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, "");
        // Returning string after removing zeros
        return sb.toString();
    // Method 2
    // Main driver method
    public static void main(String[] args)
        // Sample string input
        String str = "00000123569";
        // Calling method 1 to count leading zeroes
        // in above string
        str = removeZero(str);
        // Printing leading zeros inside string



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.

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!