Skip to content

Latest commit

 

History

History
31 lines (21 loc) · 1.09 KB

File metadata and controls

31 lines (21 loc) · 1.09 KB

Java 程序:从字符串中删除所有空格

原文: https://www.programiz.com/java-programming/examples/remove-whitespaces

在此程序中,您将学习如何使用 Java 中的正则表达式删除给定字符串中的所有空格。

示例:删除所有空格的程序

public class Whitespaces {

    public static void main(String[] args) {
        String sentence = "T    his is b  ett     er.";
        System.out.println("Original sentence: " + sentence);

        sentence = sentence.replaceAll("\\s", "");
        System.out.println("After replacement: " + sentence);
    }
}

运行该程序时,输出为:

Original sentence: T    his is b  ett     er.
After replacement: Thisisbetter.

在上面的程序中,我们使用StringreplaceAll()方法删除并替换字符串sentence中的所有空格。

我们使用正则表达式\\s查找字符串中的所有空白字符(制表符,空格,换行符等)。 然后,将其替换为""(空字符串字面值)。