Java Program to remove all white spaces from a string

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 ).
let’s begin.


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 “”.

Program:

The output of removing spaces from a string in java:

java to remove white spaces from string

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.

Program

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

java to remove white spaces from string

String Anagram
How to remove duplicates from ArrayList in java
How to find the duplicate characters in a string in java

1 thought on “Java Program to remove all white spaces from a string”

Comments are closed.