Remove duplicate whitespaces from a String in Java
This post will discuss how to remove duplicate whitespaces from a String in Java.
1. Using String.replaceAll() method
To remove duplicate whitespaces from a string, you can use the regular expression \s+ which matches with one or more whitespace characters, and replace it with a single space ' '. This can be done using the replaceAll() method, which replaces each substring of the string that matches the given regex with the specified replacement.
|
1 2 3 4 5 6 7 8 |
public class Main { public static void main(String[] args) { String s = "Hello World"; String filtered = s.replaceAll("\\s+", " "); System.out.println(filtered); } } |
Output:
Hello World
The above solution does not remove the leading and trailing spaces from the string. You can call the trim() method to eliminate spaces at the beginning and end of the string. It can be called before (or after) making a call to the replaceAll() method.
|
1 2 3 4 5 6 7 8 |
public class Main { public static void main(String[] args) { String s = " Hello World "; String filtered = s.trim().replaceAll("\\s+", " "); System.out.println(filtered); } } |
Output:
Hello World
The regex \s+ matches with one or more whitespace characters. To match with exactly two or more whitespace characters, a better alternative is to use the regex \s{2,}.
|
1 2 3 4 5 6 7 8 |
public class Main { public static void main(String[] args) { String s = " Hello World "; String filtered = s.trim().replaceAll("\\s{2,}", " "); System.out.println(filtered); } } |
Output:
Hello World
You might want to compile the regular expression for performance boost (when regex is called multiple times):
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { private static Pattern pattern = Pattern.compile("\\s{2,}"); public static void main(String[] args) { String s = " Hello World "; String filtered = pattern.matcher(s).replaceAll(" "); System.out.println(filtered); } } |
Output:
Hello World
2. Using Apache Commons Lang
If you prefer Apache Commons Lang library, you can use the StringUtils.normalizeSpace() method for this specific task. It removes the leading and trailing whitespace from the specified string, and then replaces sequences of whitespace characters by a single space.
|
1 2 3 4 5 6 7 8 9 10 |
import org.apache.commons.lang3.StringUtils; public class Main { public static void main(String[] args) { String s = " Hello World "; String filtered = StringUtils.normalizeSpace(s); System.out.println(filtered); } } |
Output:
Hello World
That’s all about removing duplicate whitespaces from a String in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)