Remove all whitespaces from a String in Java

We can remove all whitespaces from a String in Java using the built-in method replaceAll() from a String class.

Example

public class Test {

  public static void main(String[] args) {

    String str = "Learn Java with alegrucoding.com";

    String result = str.replaceAll("\\s", "");

    System.out.println(result);

  }
}

Output: LearnJavawithalegrucoding.com


Here, we passed the regular expression ‘\\s’ that finds all white space characters in the String, and we replaced all with “” empty literal.

Another way of removing all whitespaces from a String in Java is using the StringUtils class from the Apache Commons library.

Example

import org.apache.commons.lang3.StringUtils;

public class Test {

  public static void main(String[] args) {

    String str = "Learn Java with alegrucoding.com";

    String result = StringUtils.deleteWhitespace(str);

    System.out.println(result);

  }
}

Output: LearnJavawithalegrucoding.com


That’s it!

 

Leave a Reply

Your email address will not be published. Required fields are marked *