Remove multiple spaces from String in Java example shows how to remove multiple spaces from String in Java. Example also shows how to remove multiple spaces from String using regular expression and trim
method.
How to remove multiple spaces from String in Java?
Sometimes string input contains multiple consecutive white spaces which we need to remove. Consider below given string inputs.
1 2 3 4 5 | String[] strArray = { " Hello World", "Hello World ", " Hello World " }; |
First string contains multiple spaces at the start of the string, second string element contains multiple spaces at the end of the string while third string element contains multiple spaces at start, in between and at the end of the string.
Multiple spaces can be matched with regular expression with “\\s+” pattern. “\\s” matches with any space character (i.e. space, tab, and new line character). “\\s+” matches one or more space characters.
Use replaceAll
method which accepts 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 single space at the start and end of the String. To remove that as well, use trim
method along with 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 Apache Commons library, you can use normalizeSpace
method of StringUtils class to remove multiple spaces from the String as given below. normalizeSpace
method first trims the string (thus removing all leading and trailing spaces from the string) and then it replaces multiple spaces with 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 |
Please let us know your views in the comments section below.
Add Comment