在此程序中,您将学习使用Java中的正则表达式删除给定字符串中的所有空格。
public class Whitespaces {
public static void main(String[] args) {
String sentence = "T his is b ett er! www. nhooo. com";
System.out.println("原始句子: " + sentence);
sentence = sentence.replaceAll("\\s", "");
System.out.println("替换删除空格后: " + sentence);
}
}运行该程序时,输出为:
原始句子: T his is b ett er!www. nhooo. com 替换删除空格后: Thisisbetter!www.cainiaoplus.com
在上面程序中,我们使用String的replaceAll()方法删除和替换字符串sentence中的所有空格。
我们使用正则表达式\\s查找字符串中的所有空白字符(制表符,空格,换行符等)。然后,我们将其替换为""(空字符串文字)。