Remove multiple spaces from String in Java example shows how to remove multiple consecutive spaces from string in Java using regular expression and the trim
method.
How to remove multiple spaces from String in Java?
Sometimes string input contains multiple consecutive white spaces that we need to remove. Consider below given string inputs.
1 2 3 4 5 |
String[] strArray = { " Hello World", "Hello World ", " Hello World " }; |
The first string contains multiple spaces at the start of the string, second string element contains multiple spaces at the end of the string while the third string array element contains multiple spaces at start, in between and at the end of the string.
Multiple spaces can be matched with regular expression with the “\\s+” pattern. The “\\s” pattern matches any space character (i.e. space, tab, and new line character). The “\\s+” pattern matches one or more space characters.
Use the replaceAll
method of the String class which accepts a regular expression to replace one or more space characters with the single space to remove multiple spaces from the string as given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
package com.javacodeexamples.stringexamples; public class RemoveMultipleSpacesFromStringExample { public static void main(String[] args) { String[] strArray = { " Hello World", "Hello World ", " Hello World " }; for(String string : strArray){ System.out.println( string.replaceAll("\\s+", " ") ); } } } |
Output
1 2 3 |
Hello World Hello World Hello World |
Our pattern removed multiple spaces from the middle of the string, but it still left a single space at the start and end of the String. To remove that as well, use trim
method along with the replaceAll
method as given below.
1 |
System.out.println( string.trim().replaceAll("\\s+", " ") ); |
Output
1 2 3 |
Hello World Hello World Hello World |
Finally, if you are using the Apache Commons library, you can use the normalizeSpace
method of the StringUtils class to remove multiple spaces from the string as given below. The normalizeSpace
method first trims the string (thus removing all leading and trailing spaces from the string) and then it replaces multiple spaces with a single space.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
package com.javacodeexamples.stringexamples; import org.apache.commons.lang3.StringUtils; public class RemoveMultipleSpacesFromStringExample { public static void main(String[] args) { String[] strArray = { " Hello World", "Hello World ", " Hello World " }; for(String string : strArray){ System.out.println(StringUtils.normalizeSpace(string)); } } } |
Output
1 2 3 |
Hello World Hello World Hello World |
This example is a part of the Java String tutorial.
Please let me know your views in the comments section below