java如何去掉空格
去除字符串中的空格
在Java中,去除字符串中的空格可以通过多种方法实现,以下是几种常见的方式:
使用String类的replaceAll方法
String str = " Hello World ";
String result = str.replaceAll("\\s+", "");
System.out.println(result); // 输出: HelloWorld
\\s+匹配任意空白字符(包括空格、制表符、换行符等),替换为空字符串。
使用String类的trim方法
String str = " Hello World ";
String result = str.trim();
System.out.println(result); // 输出: Hello World
trim()只能去除字符串首尾的空格,中间的空格不会被去除。
使用StringUtils类的deleteWhitespace方法(Apache Commons Lang库)
import org.apache.commons.lang3.StringUtils;
String str = " Hello World ";
String result = StringUtils.deleteWhitespace(str);
System.out.println(result); // 输出: HelloWorld
StringUtils.deleteWhitespace()会去除字符串中的所有空白字符。
使用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();
System.out.println(result); // 输出: HelloWorld
通过过滤掉所有空白字符,重新构建字符串。
去除字符串中的特定空格
如果只需要去除字符串中的空格(不包括其他空白字符),可以使用以下方法:
使用String类的replace方法
String str = " Hello World ";
String result = str.replace(" ", "");
System.out.println(result); // 输出: HelloWorld
replace()方法会替换所有匹配的空格。
使用正则表达式去除首尾空格
String str = " Hello World ";
String result = str.replaceAll("^\\s+|\\s+$", "");
System.out.println(result); // 输出: Hello World
^\\s+匹配字符串开头的空格,\\s+$匹配字符串结尾的空格。
性能考虑
对于大量字符串操作,replaceAll和正则表达式可能性能较差。如果性能是关键,可以考虑使用StringBuilder手动处理:
String str = " Hello World ";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
if (!Character.isWhitespace(str.charAt(i))) {
sb.append(str.charAt(i));
}
}
String result = sb.toString();
System.out.println(result); // 输出: HelloWorld
这种方法虽然代码量较多,但在处理大量数据时性能更好。







