Computer >> Computer tutorials >  >> Programming >> Java

Java Program to Remove leading zeros


In this article, we will understand how to remove leading zeros. A string with leading zeroes or one’s can be removed using a simple iterator and replacing the zeroes with a blank space.

Below is a demonstration of the same −

Suppose our input is

Input string: 00000445566

The desired output would be

Result: 445566

Algorithm

Step 1 - START
Step 2 - Declare a string value namely input_string and a StringBuffer object namely string_buffer.
Step 3 - Define the values.
Step 4 - Iterate over the characters of the string using a while loop, replace the zero values with “”(blank space) using .replace() function.
Step 5 - Display the result
Step 6 - Stop

Example 1

Here, we bind all the operations together under the ‘main’ function.

import java.util.Arrays;
import java.util.List;
public class RemoveZero {
   public static void main (String[] args) {
      System.out.println("Required packages have been imported");
      String input_string = "00000445566";
      System.out.println("\nThe string is defined as: " +input_string);
      int i = 0;
      while (i < input_string.length() && input_string.charAt(i) == '0')
         i++;
      StringBuffer string_buffer = new StringBuffer(input_string);
      string_buffer.replace(0, i, "");
      input_string = string_buffer.toString();
      System.out.println(input_string);
   }
}

Output

Required packages have been imported

The string is defined as: 00000445566
445566

Example 2

Here, we encapsulate the operations into functions exhibiting object-oriented programming.

import java.util.Arrays;
import java.util.List;
public class RemoveZero {
   public static String remove_zero(String input_string) {
      int i = 0;
      while (i < input_string.length() && input_string.charAt(i) == '0')
         i++;
      StringBuffer string_buffer = new StringBuffer(input_string);
      string_buffer.replace(0, i, "");
      return string_buffer.toString();
   }
   public static void main (String[] args) {
      System.out.println("Required packages have been imported");
      String input_string = "00000445566";
      System.out.println("\nThe string is defined as: " +input_string);
      input_string = remove_zero(input_string);
      System.out.println(input_string);
   }
}

Output

Required packages have been imported

The string is defined as: 00000445566
445566