Java程式用於移除字串中的所有空格


在本文中,我們將瞭解如何在Java中從字串中移除所有空格。Java中的String類表示用雙引號括起來的一系列字元。從字串中移除空格是一種常見的操作,尤其是在處理使用者輸入或清理資料時。replaceAll()方法與正則表示式一起使用,以匹配空格字元並將其替換為空字串

問題陳述

給定一個包含空格的字串,編寫一個Java程式來移除字串中的所有空格。
輸入
Initial String = "Java programming is fun to learn."
輸出
String after removing white spaces = "Javaprogrammingisfuntolearn.

從字串中移除空格的步驟

以下是從字串中移除空格的步驟

  • 宣告一個字串變數來儲存輸入。
  • 使用 replaceAll() 方法和正則表示式“\s”將所有空格字元替換為空字串
  • 顯示修改後的字串。

Java程式用於移除字串中的空格

以下是從字串中移除空格的示例

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

輸出

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

The string after replacing white spaces: Javaprogrammingisfuntolearn.

將移除空格的操作封裝到Java中的函式中

以下是將移除空格的操作封裝到Java中的函式中的示例

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

輸出

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

The string after replacing white spaces: Javaprogrammingisfuntolearn.

程式碼說明

程式首先定義一個帶有空格的字串input_stringreplaceAll()方法使用正則表示式\s將所有空格替換為空字串。第一個示例在主函式中執行此操作,而第二個程式使用string_replace方法以提高模組化。兩種方法都刪除了空格,輸出顯示了結果。

更新於: 2024年11月7日

286 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告