Remove All Whitespace from String in Java



In this article, we will learn how to remove all whitespaces from a string in Java using the replaceAll() method. This method replaces substrings that match a given regular expression with a specified replacement. By replacing spaces with an empty string, we can remove all whitespaces from the input string.

Problem Statement

A string with some spaces is given. We should remove all whitespaces from the string using the replaceAll() method.

Input

Initial String = "Hi how are you Welcome to Tutorialspoint.com"

Output

String after removing whitespaces = "HihowareyouWelcometoTutorialspoint.com"

Steps to remove whitespaces from a string

The following are the steps to remove whitespaces from a string

  • Create a string containing some whitespaces.
  • Use the replaceAll() method to replace spaces with an empty string.
  • Print the output string to display the result without whitespaces.

Java program to remove all whitespaces from a string

The following is an example of removing all whitespaces from a string

import java.io.*;
public class Test {
 public static void main(String args[]) {
String Str = new String("Hi how are you Welcome to Tutorialspoint.com");
System.out.print("Return Value :" );
System.out.println(Str.replaceAll(" ", ""));
 }
}

Output

Return Value :HihowareyouWelcometoTutorialspoint.com

Code Explanation

In this program, we create a string that contains spaces between words. The replaceAll() method is then used to replace every occurrence of a space character with an empty string. As a result, all spaces are removed from the original string. The program outputs the modified string without any whitespaces, which is displayed as a continuous sequence of characters.

Updated on: 2024-11-04T18:42:42+05:30

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements