」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 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
瀏覽:141

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