用特定字元替換字串空格的 Java 程式


在本文中,我們將瞭解如何用特定字元替換字串空格。字串是一種包含一個或多個字元且用雙引號(“ ”)引起來的資料型別。

以下是相同內容的演示:

假設我們的輸入為

Input string: Java Program is fun to learn
Input character: $

期望的輸出將為

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

演算法

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

示例 1

在此,我們將所有操作繫結在 “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);
   }
}

輸出

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

示例 2

在此,我們將操作封裝到函式中,以展示面向物件程式設計。

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

輸出

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

更新於: 30-Mar-2022

984 瀏覽量

開啟你的職業生涯

透過完成課程獲得認證

立即開始
廣告