Given a string of digits, remove leading zeros from it.
Examples:
Input : 00000123569 Output : 123569 Input : 000012356090 Output : 12356090
We use StringBuffer class as Strings are immutable.
1) Count leading zeros.
2) Use StringBuffer replace function to remove characters equal to above count.
// Java program to remove leading/preceding zeros // from a given string import java.util.Arrays; import java.util.List; /* Name of the class to remove leading/preceding zeros */class RemoveZero { public static String removeZero(String str) { // Count leading zeros int i = 0; while (i < str.length() && str.charAt(i) == '0') i++; // 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); System.out.println(str); } } |
Output:
123569
Remove leading 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 contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. 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.
Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.
Recommended Posts:
- Trim (Remove leading and trailing spaces) a string in Java
- Removing elements between the two zeros
- Remove all non-alphabetical characters of a String in Java
- How to remove all non-alphanumeric characters from a string in Java
- Remove extra delimiter from a String in Java
- How to remove all white spaces from a String in Java?
- Remove first and last character of a string in Java
- Different Ways to Remove all the Digits from String in Java
- Remove a given word from a String
- Remove uppercase, lowercase, special, numeric, and non-numeric characters from a String
- How to remove an element from ArrayList in Java?
- ArrayList and LinkedList remove() methods in Java with Examples
- TreeSet remove() Method in Java
- EnumMap remove() Method in Java
- LinkedList remove() Method in Java
- HashSet remove() Method in Java
- PriorityQueue remove() Method in Java
- HashMap remove() Method in Java
- TreeMap remove() Method in Java
- ArrayDeque remove() Method in Java
Improved By : Sanjeev Kumar Jha

