”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > input: How Can I Efficiently Remove Multiple Spaces and Trim Leading/Trailing Spaces in Java? output: Java高效去除多余空格及首尾空格方法

input: How Can I Efficiently Remove Multiple Spaces and Trim Leading/Trailing Spaces in Java? output: Java高效去除多余空格及首尾空格方法

发布于2025-04-29
浏览:632

How Can I Efficiently Remove Multiple Spaces and Trim Leading/Trailing Spaces in Java?
java:用单个空间替换多个空间,并修剪领先和落后空间

此解决方案利用trim()方法删除了前导和尾随空间,然后使用spepaceAll()将多个空间组合到单个空间中:

regex-inly 虽然读取较少,但使用复杂的正则表达式解决问题是可行的,可以解决问题:

“ x”, “ 1 2 3”, “”, “”, }; for(字符串测试:测试){ system.out.format(“ [%s]%n”, test.replaceall(“^ | $ |()”,“ $ 1”) ); } [

solution 1:

trim()删除所有领先和落后的空间,而septaceall()替换空间替换了单个空间。一个步骤中相同的结果。 It matches and replaces sequences of spaces at the beginning, end, or middle of the string with either an empty string (to remove extra spaces) or a single captured space (to keep single spaces intact).

Additional Resources

String after = before.trim().replaceAll("  ", " ");

[String.trim()文档](https://docs.oracle.com/javase/7/docs/api/java/java/lang/lang/string.html#trim----) [正则表达式重复模式] Anchors](https://www.regular-expressions.info/anchors)

最新教程 更多>

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3