從 Java 字串中移除換行、空格和製表符


如需從字串中移除換行符、空格符和製表符,請使用空字元替換,如下所示。

replaceAll("[\
\t ]", "");

上述示例中,我們會使用 replaceAll(),從而替換換行符、製表符和空格符。

這是一個完整的示例。

示例

 現場演示

public class Demo {
   public static void main(String[] args) {
      String originalStr = "Demo
\tText";       System.out.println("Original String with tabs, spaces and newline:
"+originalStr);       originalStr = originalStr.replaceAll("[\
\t ]", "");       System.out.println("
String after removing tabs, spaces and new line: "+originalStr);    } }

輸出

Original String with tabs, spaces and newline:
Demo
Text
String after removing tabs, spaces and new line: DemoText

更新於: 2020 年 6 月 27 日

17k+ 瀏覽

開啟你的 職業生涯

完成課程即可獲得認證

開始學習
廣告
© . All rights reserved.