在 Java 中,“去除空格”有多种含义,常见情况如下:
使用 trim()(Java 11 之前)或 strip()(Java 11+)
String s = " hello world ";
System.out.println(s.trim()); // "hello world"
System.out.println(s.strip()); // "hello world"
✅ 区别:
trim():只去除 ASCII 空格(\u0020)strip():去除所有 Unicode 空白字符(推荐)使用 replaceAll()
String s = "he llo wo rld";
String result = s.replaceAll(" ", "");
System.out.println(result); // "helloworld"
或去除所有空白字符(空格、Tab、换行等):
String result = s.replaceAll("\\s+", "");
String s = "hello world";
String result = s.replaceAll("\\s+", " ");
System.out.println(result); // "hello world"
s.stripLeading();
s.stripTrailing();
❌ trim() 不能去 Unicode 空格(如全角空格)
✅ 用 strip() 或 replaceAll("\\s", "")
如果你有具体场景(如用户输入、文件解析、JSON 处理),可以告诉我,我给你更合适的写法。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。