java:用單個空間替換多個空間,並修剪領先和落後空間
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