Saturday 6 February 2016

How to remove whitespace in a String in Java

The TRIM method in String class just removes the white-spaces that are there at the start and end of the String.  It does not remove the white-spaces which are available in any other position.

Below is the code snippet to remove the white space,

String demo1 = "All is well";
Demo1 = demo1.replaceAll("\\s", ""); //or demo1 = demo1.replaceAll("\\s+", "");
System.out.println("Printing String ::: " + demo1);

Output:

Printing String ::: Alliswell

Note: The replaced string should be assigned to same variable or to a different variable in-order to get the updated value.

Below is the error instance,

String demo2 = "All is well";
Demo2.replaceAll("\\s", "");
System.out.println("Printing String ::: " + demo2);

Output:

Printing String ::: All is well

The variable “demo2” will remain unchanged since the data is not assigned after replacement.

No comments:

Post a Comment