How to remove leading zeros from a string in Java

In this tutorial, you’ll learn how to remove leading zeros from a given string in Java. There are many ways in which you could do that. For example, use string functions or consider string as a character array and perform tasks or use both string and array functions.

Example:

Input is:

002547852113

The output will be:

2547852113

Using String Functions to remove leading or prefix zeros from a string in Java

The first method that we are going to use is by using string function replaceAll()

package javaapplication16;
import java.util.Scanner;
public class JavaApplication16 {

   public static void main(String[] args) {
        String zero = "0";
       Scanner sc = new Scanner(System.in);
      System.out.println("Enter a String ");
      String str = sc.next();
      str = str.replaceAll(zero, "");
      System.out.println(str);
    }
    
}

Output:

Enter a String 
00002333848457
2333848457

Using Array and String Functions

The second method used is using both string and array functions. Don’t forget to import the Arrays PackageĀ before using Array functions in Java.

package javaapplication16;
import java.util.Arrays;
public class JavaApplication16 {

   public static void main(String[] args) {
        String str = "000088469822";
      int l = 0;
      char[] array = str.toCharArray();
      l = array.length;
      int firstNonZeroAt = 0;
      for(int i=0; i<l; i++) {
         if(!String.valueOf(array[i]).equalsIgnoreCase("0")) {
            firstNonZeroAt = i;
            break;
         }
      }
      char [] newArray = Arrays.copyOfRange(array, firstNonZeroAt,l);
      String resultString = new String(newArray);
      System.out.println(resultString);
    }
    
}

Output:

88469822

Conclusion

This tutorial was basically used to give you the knowledge of how to use string functions and the Array functions in Java as and when required. There are other functions also apart from being used in the program, this was just a glimpse of them.

Leave a Reply

Your email address will not be published. Required fields are marked *