Computer >> Máy Tính >  >> Lập trình >> Java

Chương trình Java để loại bỏ các số không ở đầu

Trong bài viết này, chúng ta sẽ hiểu làm thế nào để loại bỏ các số không ở đầu. Có thể xóa một chuỗi có các số 0 đứng đầu hoặc một số bằng một trình lặp đơn giản và thay thế các số 0 bằng một khoảng trống.

Dưới đây là một minh chứng về điều tương tự -

Giả sử đầu vào của chúng tôi là -

Input string: 00000445566

Đầu ra mong muốn sẽ là -

Result: 445566

Thuật toán

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

Ví dụ 1

Ở đây, chúng tôi liên kết tất cả các hoạt động với nhau trong hàm "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);
   }
}

Đầu ra

Required packages have been imported

The string is defined as: 00000445566
445566

Ví dụ 2

Ở đây, chúng tôi đóng gói các hoạt động thành các hàm thể hiện lập trình hướng đối tượng.

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

Đầu ra

Required packages have been imported

The string is defined as: 00000445566
445566