本文目录导读:

- 去除首尾空格(最常用)
- 去除所有空格(中间空格也去除)
- 去除所有空白字符(包括回车、换行、制表符等)
- 去除首尾空白字符(更全面的版本,Java 11+)
- 去除中文全角空格
- 综合示例:处理各种常见情况
- 性能对比和选择建议
- 注意事项
在Java中去除字符串空格有多种方法,以下是常见的几种场景和对应的解决方案:
去除首尾空格(最常用)
String str = " Hello World ";
String result = str.trim();
System.out.println("[" + result + "]"); // [Hello World]
注意:trim() 只去除ASCII码中的空格(字符码32),不能去除全角空格或其他空白字符。
去除所有空格(中间空格也去除)
// 方法1:使用 replaceAll
String str = " H e l l o World ";
String result = str.replaceAll(" ", "");
System.out.println(result); // HelloWorld
// 方法2:使用 replace(更高效,但只针对单个空格)
String result2 = str.replace(" ", "");
System.out.println(result2); // HelloWorld
去除所有空白字符(包括回车、换行、制表符等)
String str = " H\te l\tl\no W\r\norld ";
String result = str.replaceAll("\\s", "");
System.out.println(result); // HelloWorld
去除首尾空白字符(更全面的版本,Java 11+)
// Java 11 引入的 strip() 方法
String str = " \n\tHello World\n\t ";
String result = str.strip();
System.out.println("[" + result + "]"); // [Hello World]
// stripLeading() - 只去除开头的空白
String resultLeading = str.stripLeading();
System.out.println("[" + resultLeading + "]"); // [Hello World\n\t ]
// stripTrailing() - 只去除结尾的空白
String resultTrailing = str.stripTrailing();
System.out.println("[" + resultTrailing + "]"); // [ \n\tHello World]
strip() vs trim() 的区别:
trim():只处理字符码 ≤ 32 的字符strip():处理所有Unicode空白字符(包括全角空格、不换行空格等)
去除中文全角空格
String str = " Hello World ";
// 去除全角空格(中文全角空格是\u3000)
String result = str.replaceAll("[\u3000]", "");
System.out.println(result); // HelloWorld
// 同时去除半角空格和全角空格
String result2 = str.replaceAll("[\\s\u3000]", "");
System.out.println(result2); // HelloWorld
综合示例:处理各种常见情况
public class StringTrimExample {
public static void main(String[] args) {
// 测试各种字符串
String[] tests = {
" Hello World ", // 前后半角空格
" Hello World ", // 前后全角空格
" H e l l o W o r l d ", // 中间多个空格
"\n\tHello\n\tWorld\n\t", // 包含转义字符
"Hello World", // 中间全角空格
"" // 空字符串
};
for (String str : tests) {
System.out.println("原始: [" + str + "]");
System.out.println("trim: [" + str.trim() + "]");
System.out.println("strip: [" + str.strip() + "]");
System.out.println("remove all: [" + str.replaceAll("\\s", "") + "]");
System.out.println("---");
}
}
}
性能对比和选择建议
| 场景 | 推荐方法 | 说明 |
|---|---|---|
| 去除首尾半角空格 | trim() |
最常用,性能好 |
| 去除首尾所有空白(Java 11+) | strip() |
更全面,支持Unicode |
| 去除所有空格(只保留非空格字符) | replace(" ", "") |
只处理普通空格,效率高 |
| 去除所有空白字符 | replaceAll("\\s", "") |
正则表达式,最彻底但性能稍差 |
| 复杂替换需求 | replaceAll("regex", "") |
使用正则表达式灵活处理 |
注意事项
- 不可变性:String是不可变的,所有方法都返回新的字符串
- 空指针异常:如果原字符串为null,调用这些方法会报错,建议先判空
- 性能考虑:简单场景用
trim()或strip();需要大量替换时考虑使用 StringBuilder
选择哪个方法取决于你的具体需求:是只需要去除首尾空格,还是需要去除所有空格?是否要考虑Unicode空白字符?