How do I trim spaces inside leaving only one space taking consideration of performance?
Input: AA BB Output: AA BB Input: A A Output: A A
System.out.println(" AA BB".replaceAll("\\s+", " ").trim());
Output:
AA BB
Note: Unlike some of the other solutions here, this also replaces a single tab with a single space. If you don't have any tabs you can use " {2,}" instead which will be even faster:
System.out.println(" AA BB".replaceAll(" {2,}", " ").trim());
Replace two or more spaces "\\s{2,}"
by a single space " "
and do a trim()
afterwards to get rid of the leading and trailing spaces as you showed in the 1st example.
output = input.replaceAll("\\s{2,}", " ").trim();
s = s.replaceAll("\\s+", " " ).trim();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With