English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Removing Leading Zeros from String in Java

In Java, there are many methods to remove leading zeros from strings. Here, we will use some basic functions of String and Arrays classes to remove leading zeros from strings.

Therefore, this method first converts the string to a character array to make it easier to evaluate each character in the string. Now, it seems simple to compare each character and find the first non-zero character. However, there is a limitation here, in Java, arrays do not have an equals method to compare their values, so here we will use}}valueOf()String class methods to compare each character.

Now that we have obtained the position of the first non-zero digit in the string, the only thing left to do is to trim the array to the position of the first non-zero digit. For this usagecopyOfRange()Usage of three parameters, one is the original array, the second is the starting position to copy, and the third is the position to copy to.

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 Result

myCSV.csv file created using the following text

first non zero digit at : 3
99898979