How to remove all white spaces from String in java

In this post, we will see how to remove all white spaces from String in java.

There are multiple ways to remove spaces from String.
  1. Using ReplaceAll
  2. Using Iteration

Using ReplaceAll :

You can simply call ReplaceAll method to remove white spaces as shown below.
String result1 = str.replaceAll("\\s", "");

Using iteration :

You can iterate over String using charAt and check if Character is whitespace or not.

Java Program to remove all white spaces from String

package org.arpit.java2blog;

public class StringRemoveSpacesAllMain {

 public static void main(String[] args) {
  String str = "     Hello world from   java2blog.com  ";
  System.out.println("------------------------------");
  System.out.println("Using replaceAll");
  System.out.println("------------------------------");

                // Using replaceAll
  String result1 = str.replaceAll("\\s", "");
  System.out.println(result1);

  String result2 = "";
  // Using iteration
  System.out.println("\n------------------------------");
  System.out.println("Using Iteration");
  System.out.println("------------------------------");
  for (int i = 0; i < str.length(); i++) {
   if (!Character.isWhitespace(str.charAt(i))) {
    result2 += str.charAt(i);
   }
  }
  System.out.println(result2);
 }
}

When you run above program, you will get below output:
------------------------------
Using replaceAll
------------------------------
Helloworldfromjava2blog.com

------------------------------
Using Iteration
------------------------------
Helloworldfromjava2blog.com

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012