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

Chương trình Java để thay thế các khoảng trắng của một chuỗi bằng một ký tự cụ thể

Trong bài này, chúng ta sẽ hiểu cách thay thế khoảng trắng của một chuỗi bằng một ký tự cụ thể. 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 Program is fun to learn
Input character: $

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

The string after replacing spaces with given character is:
Java$Program$is$fun$to$learn

Thuật toán

Step 1 - START
Step 2 - Declare a string namely input_string, a char namely input_character.
Step 3 - Define the values.
Step 4 - Using the function replace(), replace the white space with the specified character.
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 Program is fun to learn";
      System.out.println("The string is defined as: " +input_string);
      char input_character = '$';
      System.out.println("The character is defined as: " +input_character);
      input_string = input_string.replace(' ', input_character);
      System.out.println("The string after replacing spaces with given character is: ");
      System.out.println(input_string);
   }
}

Đầu ra

The string is defined as: Java Program is fun to learn
The character is defined as: $
The string after replacing spaces with given character is:
Java$Program$is$fun$to$learn

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 {
   static void space_replace(String input_string, char input_character){
      input_string = input_string.replace(' ', input_character);
      System.out.println("The string after replacing spaces with given character is: ");
      System.out.println(input_string);
   }
   public static void main(String[] args) {
      String input_string = "Java Program is fun to learn";
      System.out.println("The string is defined as: " +input_string);
      char input_character = '$';
      System.out.println("The character is defined as: " +input_character);
      space_replace(input_string, input_character);
   }
}

Đầu ra

The string is defined as: Java Program is fun to learn
The character is defined as: $
The string after replacing spaces with given character is:
Java$Program$is$fun$to$learn