Remove Leading Zeros From String in Java


There are many approaches to remove leading zeroes from a string in Java. Here we will use some basic functions of String and Arrays class which to remove leading zeroes from a string.

So this approach proceed as first convert string to a character array so that evaluation of each character in string becomes simpler. Now it seems simple that compare each character and find first non zero characters. But here is a constraint that in Java that array doesn't have equals method to compare its value so here we will use valueOf() method of String class to compare each character.

Now we get the position of first non zero digit in our String the only thing remaining is to trim our array upto first non zero digit position. For this use copyOfRange() method which takes three arguments one is original array second is from a position where a copy is to be started and third is to position upto which copy is to be done.

Example

public class RemoveLeadingZeroes {
   public static void main(String[] args) {
      String str = "00099898979";
      int arrayLength = 0;
      char[] array = str.toCharArray();
      arrayLength = array.length;
      int firstNonZeroAt = 0;
      for(int i=0; i<array.length; i++) {
         if(!String.valueOf(array[i]).equalsIgnoreCase("0")) {
            firstNonZeroAt = i;
            break;
         }
      }
      System.out.println("first non zero digit at : " +firstNonZeroAt);
      char [] newArray = Arrays.copyOfRange(array, firstNonZeroAt,arrayLength);
      String resultString = new String(newArray);
      System.out.println(resultString);
   }
}

Output

myCSV.csv file created with following text

first non zero digit at : 3
99898979

Updated on: 25-Jun-2020

295 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements