The replaceAll() method of the String class accepts two strings representing a regular expression and a replacement String and replaces the matched values with given String.
Following is the regular expression to match the leading zeros of a string −
The ^0+(?!$)";
To remove the leading zeros from a string pass this as first parameter and “” as second parameter.
Example
The following Java program reads an integer value from the user into a String and removes the leading zeroes from it using the Regular expressions.
import java.util.Scanner;
public class LeadingZeroesRE {
public static String removeLeadingZeroes(String str) {
String strPattern = "^0+(?!$)";
str = str.replaceAll(strPattern, "");
return str;
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter an integer: ");
String num = sc.next();
String result = LeadingZeroesRE.removeLeadingZeroes(num);
System.out.println(result);
}
}
Output
Enter an integer:
000012336000
12336000=====================================https://www.geeksforgeeks.org/remove-leading-zeros-from-a-number-given-as-a-string/
Time Complexity: O(N)
Auxiliary Space: O(N)
Space-Efficient Approach:
Follow the steps below to solve the problem in constant space using Regular Expression:
- Create a Regular Expression as given below to remove the leading zeros
regex = “^0+(?!$)”
where:
^0+ match one or more zeros from the beginning of the string.
(?!$)is a negative look-ahead expression, where “$” means the endof the string.
-
Use the inbuilt replaceAll() method of the String class which accepts two parameters, a Regular Expression, and a Replacement String.
-
To remove the leading zeros, pass a Regex as the first parameter and empty string as the second parameter.
-
This method replaces the matched value with the given string.
Below is the implementation of the above approach:
Original: https://www.cnblogs.com/kungfupanda/p/15989458.html
Author: 功夫 熊猫
Title: How to remove leading zeros from alphanumeric text?
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/552363/
转载文章受原作者版权保护。转载请注明原作者出处!