Removing leading zeros from a String using apache commons library in Java

JavaObject Oriented ProgrammingProgramming

The stripStart() method of the org.apache.commons.lang.StringUtils class accepts two strings and removes the set of characters represented by the second string from the string of the first string.

To remove leading zeros from a string using apache communal library −

  • Add the following dependency to your pom.xml file

<dependency>
   <groupId>org.apache.commons</groupId>
   <artifactId>commons-lang3</artifactId>
   <version>3.9</version>
</dependency>
  • Get the string.

  • Pass the obtained string as first parameter and a string holding 0 as second parameter to the stripStart() method of the StringUtils class.

Example

The following Java program reads an integer value from the user into a String and removes the leading zeroes from it using the stripStart() method of the StringUtils class.

import java.util.Scanner;
import org.apache.commons.lang3.StringUtils;
public class LeadingZeroesCommons {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter a String: ");
      String str = sc.nextLine();
      String result = StringUtils.stripStart(str, "0");
      System.out.println(result);
   }
}

Output

Enter a String:
000Hello how are you
Hello how are you
raja
Published on 15-Oct-2019 07:30:38
Advertisements