Java Program to Remove All Whitespaces from a String

JavaCampus InterviewServer Side ProgrammingProgramming

In this article, we will understand how to remove all whitespaces from a string. String is a datatype that contains one or more characters and is enclosed in double quotes(“ ”).

Below is a demonstration of the same −

Suppose our input is

Input string: Java programming is fun to learn.

The desired output would be

The string after replacing white spaces: Javaprogrammingisfuntolearn.

Algorithm

Step 1 - START
Step 2 - Declare two strings namely String input_string and result.
Step 3 - Define the values.
Step 4 - Use the function replaceAll("\\s", "") to replaces all the white spaces with blank spaces.
Step 5 - Display the result
Step 6 - Stop

Example 1

Here, we bind all the operations together under the ‘main’ function.

public class Demo {
   public static void main(String[] args) {
      String input_string = "Java programming is fun to learn.";
      System.out.println("The string is defined as: " + input_string);
      String result = input_string.replaceAll("\\s", "");
      System.out.println("\nThe string after replacing white spaces: " + result);
   }
}

Output

The string is defined as: Java programming is fun to learn.

The string after replacing white spaces: Javaprogrammingisfuntolearn.

Example 2

Here, we encapsulate the operations into functions exhibiting object-oriented programming.

public class Demo {
   public static String string_replace(String input_string){
      String result = input_string.replaceAll("\\s", "");
      return result;
   }
   public static void main(String[] args) {
      String input_string = "Java programming is fun to learn.";
      System.out.println("The string is defined as: " + input_string);
      String result = string_replace(input_string);
      System.out.println("\nThe string after replacing white spaces: " + result);
   }
}

Output

The string is defined as: Java programming is fun to learn.

The string after replacing white spaces: Javaprogrammingisfuntolearn.
raja
Updated on 30-Mar-2022 06:49:04

Advertisements