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

Chương trình Java để loại bỏ tất cả khoảng trắng khỏi chuỗi

Trong bài viết này, chúng ta sẽ hiểu cách xóa tất cả các khoảng trắng khỏi một chuỗi. Chuỗi là một kiểu dữ liệu chứa một hoặc nhiều ký tự và được đặt trong dấu ngoặc kép (“”).

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: Java programming is fun to learn.

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

The string after replacing white spaces: Javaprogrammingisfuntolearn.

Thuật toán

Step 1 - START
Step 2 - Declare two strings namely String input_string and result.
Step 3 - Define the values.
Step 4 - Use the function replaceAll("\\s", "") to replaces all the white spaces with blank spaces.
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".

public class Demo {
   public static void main(String[] args) {
      String input_string = "Java programming is fun to learn.";
      System.out.println("The string is defined as: " + input_string);
      String result = input_string.replaceAll("\\s", "");
      System.out.println("\nThe string after replacing white spaces: " + result);
   }
}

Đầu ra

The string is defined as: Java programming is fun to learn.

The string after replacing white spaces: Javaprogrammingisfuntolearn.

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.

public class Demo {
   public static String string_replace(String input_string){
      String result = input_string.replaceAll("\\s", "");
      return result;
   }
   public static void main(String[] args) {
      String input_string = "Java programming is fun to learn.";
      System.out.println("The string is defined as: " + input_string);
      String result = string_replace(input_string);
      System.out.println("\nThe string after replacing white spaces: " + result);
   }
}

Đầu ra

The string is defined as: Java programming is fun to learn.

The string after replacing white spaces: Javaprogrammingisfuntolearn.