Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The Best Way of Trimming Spaces in a String

Tags:

java

regex

trim

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
like image 672
Alex Gomes Avatar asked Nov 26 '09 21:11

Alex Gomes


3 Answers

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());
like image 102
Mark Byers Avatar answered Oct 01 '22 12:10

Mark Byers


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();
like image 40
BalusC Avatar answered Oct 01 '22 12:10

BalusC


s = s.replaceAll("\\s+", " " ).trim();
like image 37
peter.murray.rust Avatar answered Oct 01 '22 11:10

peter.murray.rust