Given a string of digits, remove leading zeros from it.
Examples:
Input : 00000123569 Output : 123569 Input : 000012356090 Output : 12356090
We use the StringBuffer class as Strings are permanent.
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
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.