← All posts

How to remove white spaces in Java?

1 min read

SeriesStrings in Javapart 5 of 5
  1. How to concatenate two strings in Java
  2. How to count the occurrences of a character in Java – Three Better Ways
  3. How to use StringTokenizer in Java
  4. How to split a String in Java
  5. How to remove white spaces in Java?

Removing white spaces in Java is simple. All we have to do is to use [Regex][1] and replaceAll() method of String class. A small tutorial is given below.

remove white spaces in java {.offscreen}

Tutorial – Remove white spaces in Java

package com.javaindetail.ReplaceWhiteSpaces;

public class ReplaceSpaces {

  public static void main(String[] args) {
    
    String sentence = "welcome      to   javaindetail.com this website is all about tutorials";
    System.out.println("Before replacing white spaces :: "+sentence);
    sentence = sentence.replaceAll("\s", ""); //remove white spaces in Java using regex
    System.out.println("After replacing white spaces :: "+sentence);

  }

}

Output

Before replacing white spaces :: welcome      to   javaindetail.com this website is all about tutorials
After replacing white spaces :: welcometojavaindetail.comthiswebsiteisallabouttutorials