使用正则表达式

在正则表达式中,空格用 "\\s"表示。

如果有多个连续的空格,请使用 "\\s+"
它匹配一个或者多个空格。

我们可以使用 String.replaceAll()方法在字符串中进行搜索和替换。

public class Main 
{
    public static void main(String[] args) 
    {
        String sentence = " on it road ";
        System.out.println("Oroirnal sentence: " + sentence);
        sentence = sentence.replaceAll("\s+", "");
        System.out.println("After replacement: " + sentence);
    }
}

程序输出。

Oroirnal sentence:  on it road
After replacement: onitroad
Java 如何删除字符串中的所有空格
欢迎 on it road

使用 Character.isWhitespace() 删除所有空格

遍历字符串的所有字符,使用 isWhitespace()方法检查是否为空格。

public class Main 
{
	public static void main(String[] args) 
	{
		String sentence = " on it road world ";
		System.out.println("Oroirnal sentence: " + sentence);
		sentence = sentence.codePoints()
				.filter(c -> !Character.isWhitespace(c))
				.collect(StringBuilder::new, 
							StringBuilder::appendCodePoint, 
							StringBuilder::append).toString();
		System.out.println("After replacement: " + sentence);
	}
}

程序输出。

Oroirnal sentence:  on it road world
After replacement: onitroadworld
日期:2020-09-17 00:09:36 来源:oir作者:oir