java 如何过滤空格
过滤空格的常用方法
在Java中过滤或去除字符串中的空格有多种方法,以下是几种常见的实现方式:
使用String.replaceAll()方法
通过正则表达式匹配所有空格(包括连续空格)并替换为空字符串:
String str = " Hello World ";
String result = str.replaceAll("\\s+", "");
// 输出:HelloWorld
使用String.trim()方法
仅去除字符串首尾的空格,不处理中间的空格:
String str = " Hello World ";
String result = str.trim();
// 输出:Hello World
使用Apache Commons Lang库
StringUtils类提供更灵活的空格处理:
import org.apache.commons.lang3.StringUtils;
String str = " Hello World ";
String result = StringUtils.deleteWhitespace(str);
// 输出:HelloWorld
使用Java 8的Stream API
对字符流进行过滤处理:
String str = " Hello World ";
String result = str.chars()
.filter(c -> !Character.isWhitespace(c))
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
// 输出:HelloWorld
处理特定类型空格
如需仅去除普通空格(ASCII 32)而保留制表符等:

String str = " Hello\t \nWorld ";
String result = str.replace(" ", "");
// 输出:Hello\t\nWorld
根据具体需求选择合适的方法,正则表达式方案适合处理各种空白字符,而trim()适用于简单的首尾空格清理。性能敏感场景建议进行基准测试,String.replaceAll()会编译正则表达式可能影响性能。






