Java Program to Remove all White Spaces from a String2 min read

White Space removal program in java:
In this post, we will learn how to remove white spaces from a string in java. We will learn the two ways to remove white spaces in java.

First by using in-built methods called replaceAll() and second without the use of in-built methods (for loop).


1. Java program to remove white spaces in a string using replaceAll().

This is the easiest method to remove spaces from a string in java. replaceAll() takes in two parameters, one is the string to be replaced and another one is the string to be replaced with.

In this example, we will take the string from the user input with the help of a scanner class and as a parameter, we pass “\\s” that will be replaced with “”.

Example Program:

The output of removing spaces from a string in java:


2. Java program to remove white spaces in a string using for loop

This is another method to remove white spaces. Although the above approach is recommended when it comes to creating a real-time application. This is mostly for interview programs asked.

In this method, we take the user input for string and convert them to character Array(charArray) and check those characters for white spaces by running it into the iteration. for loop will iterate until the length of the entered string.

Example Program:

The output of removing spaces from a string in java without replaceAll():


MORE

Java Program to check Krishnamurthy Number

In this tutorial, we will learn about Krishnamurthy numbers and write a Krishnamurthy Number program in Java. We will write two programs for Krishnamurthy number …
Read More

Java Program for ISBN Number

In this tutorial, we will learn about the ISBN (International Standard Book Number) and write a program to check for the ISBN Number in Java …
Read More

C++ Memory Management

Memory management refers to the process of managing the computer memory while assigning the space to the program’s variable to improve the overall performance. Requirement …
Read More

C++ Pointer to Pointer

As we know by now that a pointer stores the address of the pointed variable. But it is not the only use, pointer also stores …
Read More

C++ Passing Pointers to Functions

A function is a user-defined block of codes that executes some specific task assigned to it invoked by its name. If there is an argument …
Read More

C++ Null Pointer

We use a null pointer when we do not have the exact address to assign to a pointer. It is considered a good practice and …
Read More