从 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.