Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

선행 0을 제거하는 Java 프로그램

<시간/>

이 기사에서는 선행 0을 제거하는 방법을 이해할 것입니다. 선행 0 또는 1이 있는 문자열은 간단한 반복자를 사용하여 제거하고 0을 공백으로 바꿀 수 있습니다.

아래는 동일한 데모입니다 -

입력이 다음과 같다고 가정 -

Input string: 00000445566

원하는 출력은 -

Result: 445566

알고리즘

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

예시 1

여기에서 모든 작업을 'main' 기능 아래에 묶습니다.

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);
   }
}

출력

Required packages have been imported

The string is defined as: 00000445566
445566

예시 2

여기에서 객체 지향 프로그래밍을 나타내는 함수로 작업을 캡슐화합니다.

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);
   }
}

출력

Required packages have been imported

The string is defined as: 00000445566
445566