從 Java 中的字串中刪除所有空格


要從字串中刪除所有空格,請使用 replaceAll() 方法,並用空替換所有空格。

假設以下為我們的字串。

String str = "This is it!";

現在,讓我們替換空格,最終刪除它們。

String res = str.replaceAll("\s+","");

 即時演示

public class Demo {
   public static void main(String []args) {
      String str = "This is it!";
      System.out.println("String: "+str);
      String res = str.replaceAll("\s+","");
      System.out.println("String after deleting whitespace: "+res);
   }
}

輸出

String: This is it!
String after deleting whitespace: Thisisit!

更新於: 27-Jun-2020

126 次瀏覽

提升您的 職業

完成課程獲得認證

開始吧
廣告