Given a string containing digits, the task is to remove all leading zeros from the string while keeping the remaining digits unchanged.
- Only zeros at the beginning of the string are removed.
- Zeros occurring after a non-zero digit are preserved.
Examples:
Input : 00000123569
Output: 123569Input: 000012356090
Output: 12356090
1. Using substring()
The simplest approach is to find the index of the first non-zero character and use substring() from that index.
Approach
- Start from index
0. - Traverse the string while the current character is
'0'. - Stop when the first non-zero character is found.
- Return the substring starting from that index.
- If all characters are zeros, return
"0".
public class GFG {
static String removeLeadingZeros(String str) {
int index = 0;
// Find the first non-zero character
while (index < str.length()
&& str.charAt(index) == '0') {
index++;
}
// If all characters are zeros
if (index == str.length()) {
return "0";
}
// Remove leading zeros
return str.substring(index);
}
public static void main(String[] args) {
String str = "00000123569";
System.out.println("Original String: " + str);
System.out.println("String after removing leading zeros: "
+ removeLeadingZeros(str));
}
}
Output
Original String: 00000123569 String after removing leading zeros: 123569
Explanation: The program finds the index of the first non-zero character by traversing the string. It then uses substring(index) to remove all leading zeros and return the remaining part of the string. If the string contains only zeros, it returns "0". For "00000123569", the output is "123569".
2. Using replaceFirst()
Java's String.replaceFirst() can be used with a regular expression to remove leading zeros.
Approach
- The regular expression ^0+ matches one or more zeros (0+) from the beginning (^) of the string.
- Replace the matched zeros with an empty string.
public class GFG {
static String removeLeadingZeros(String str) {
String result = str.replaceFirst("^0+", "");
// Return "0" if the string contains only zeros
return result.isEmpty() ? "0" : result;
}
public static void main(String[] args) {
String str = "000012356090";
System.out.println("Original String: " + str);
System.out.println("String after removing leading zeros: "
+ removeLeadingZeros(str));
}
}
Output
Original String: 000012356090 String after removing leading zeros: 12356090
Explanation: The program uses replaceFirst("^0+", "") to remove one or more zeros from the beginning of the string. If all characters are zeros, the resulting string becomes empty, so the ternary operator returns "0" in that case. For the input "000012356090", the leading zeros are removed and the output is "12356090".