Learn how to remove extra white spaces between words from a String in Java. Given 3 examples remove extra spaces using regular expression, StringBuiffer
and lastly Apache Commons StringUtils
class.
1. Remove extra white spaces with StringUtils
This approach, using StringUtils.normalizeSpace() is most readable and it should be preferred way to remove unwanted white spaces between words.
This function returns the argument string with whitespace normalized by –
- using trim(String) to remove leading and trailing whitespace, and then
- replacing sequences of whitespace characters by a single space
1.1. Maven dependency
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.7</version> </dependency>
1.2. Java program to remove spaces between words
// uneven spaces between words String blogName = "how to do in java . com"; String nameWithProperSpacing = StringUtils.normalizeSpace( blogName ); System.out.println( nameWithProperSpacing );
Program output.
how to do in java . com
2. Remove extra white spaces between words with regular expression
Using regular expression, to replace 2 or more white spaces with single space, is also a good solution.
We are using regex pattern as “\\s+”.
\s
matches a space, tab, new line, carriage return, form feed or vertical tab.+
says one or more occurrences.
// uneven spaces between words String blogName = "how to do in java . com"; String nameWithProperSpacing = blogName.replaceAll("\\s+", " "); System.out.println( nameWithProperSpacing );
Program output.
how to do in java . com
Note that this method will not trim the String. That means there might be single space at start at end of string, if original string has such white spaces at beginning or end.
3. Replace multiple spaces with single space using StringBuiffer
StringBuiffer
can also help you to get string from uneven spaced strings. This is complete programmatic approach and may not be suitable for large strings.
// uneven spaces between words String blogName = "how to do in java . com"; StringTokenizer st = new StringTokenizer(blogName, " "); StringBuffer sb = new StringBuffer(); while(st.hasMoreElements()) { sb.append(st.nextElement()).append(" "); } String nameWithProperSpacing = sb.toString(); System.out.println( nameWithProperSpacing ); //trim leading and trailing white spaces nameWithProperSpacing = nameWithProperSpacing.trim(); System.out.println( nameWithProperSpacing );
Program output.
how to do in java . com
Please note that, as in case of regular expression, this method also may leave leading and trailing white spaces. So do not forget to trim the string after you have remove extra whitespaces between words in parameter string.
Happy Learning !!
Read More: