Remove All Whitespaces from a String in Java



In this article, we will understand how to remove all whitespaces from a string in Java. The String class in Java represents a sequence of characters enclosed in double-quotes. Removing whitespaces from a string is a common operation, especially when processing user input or cleaning data. The replaceAll() method is used with a regular expression to match whitespace characters and replace them with an empty string.

Problem Statement

Given a string with whitespaces, write a Java program to remove all whitespaces from the string.
Input
Initial String = "Java programming is fun to learn."
Output
String after removing white spaces = "Javaprogrammingisfuntolearn.

Steps to remove whitespaces from a string

The following are the steps to remove whitespaces from a string

  • Declare a string variable to store the input.
  • Use the replaceAll() method with the regular expression "\s" to replace all whitespace characters with an empty string.
  • Display the modified string.

Java program to remove whitespaces from a string

The following is an example of removing whitespaces from a string

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.

Encapsulate the operation to remove whitespaces into a function in Java

The following is an example of encapsulating the operation to remove whitespaces into a function in Java

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.

Code Explanation

The program starts by defining a string input_string with spaces. The replaceAll() method, using the regular expression \s, replaces all whitespaces with an empty string. The first example performs this in the main function, while the second program uses the string_replace method for better modularity. Both approaches remove the whitespaces, and the output shows the result.

Updated on: 2024-11-07T01:05:37+05:30

333 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements