Open In App

Remove Leading Zeros From String in Java

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
33 Likes
Like
Report

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

Illustrations: 

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

Example:


Output
123569

Time Complexity: O(n), where n is the length of the input string. This is because the program iterates through the input string once to count the leading zeroes and then again to remove them using the StringBuffer replace function. 
Auxiliary Space: O(n) , as the program creates a new StringBuffer object with the same length as the input string.

Approach : Using substring() method

  • Finding the index of first non zero character
  • And then use substring method from that index to length of given string
  • Assigning the substring to new string

Example:


Output
123569

Time Complexity: O(n), where n is the length of the input string 'str'. The algorithm performs a single loop through the length of the string to find the first non-zero character.
Auxiliary Space Complexity: O(n), where n is the length of the input string 'str'. The algorithm requires a string variable 'newstr' to store the modified string without leading zeros.


Next Article
Practice Tags :

Similar Reads