Remove white space characters String Java

Remove white space characters String Java

If you want to remove white space characters between two string using java you could use either regex or replace method as below sample program:

  • RemoveWhiteSpace.java
public class RemoveWhiteSpace {

	public static void main(String[] args) {
		
		String string = "Java Honk";
		System.out.println("Origional string: "+string);
		
		//Example 1: Remove white space using regex
		System.out.println("Modified String using regex: "+string.replaceAll("\\s+", ""));
		
		//Example 2: Remove white space using replace method
		System.out.println("Modified String using replace: "+string.replace(" ", ""));

	}

}
  • Output:

Remove white space characters String Java

  • For more information about String class please refer oracle documentation here

Leave a Reply

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