Java Program to Remove All Whitespace from a String

Introduction

Removing all whitespace from a string is a common task in text processing. This task helps you practice string manipulation in Java. This guide will walk you through writing a Java program that removes all spaces, tabs, and other whitespace characters from a given string.

Problem Statement

Create a Java program that:

  • Prompts the user to enter a string.
  • Removes all whitespace characters from the string.
  • Displays the string without whitespace.

Example:

  • Input: "Java programming is fun"
  • Output: "Javaprogrammingisfun"

Solution Steps

  1. Read the String: Use the Scanner class to take the string as input from the user.
  2. Remove All Whitespace: Use the replaceAll() method to remove all whitespace characters.
  3. Display the Result: Print the string without whitespace.

Java Program

// Java Program to Remove All Whitespace from a String // Author: https://www.rameshfadatare.com/ import java.util.Scanner; public class RemoveWhitespace { public static void main(String[] args) { // Step 1: Read the string from the user try (Scanner scanner = new Scanner(System.in)) { System.out.print("Enter a string: "); String input = scanner.nextLine(); // Step 2: Remove all whitespace characters String noWhitespaceString = input.replaceAll("\\s", ""); // Step 3: Display the result System.out.println("String without whitespace: " + noWhitespaceString); } } } 

Explanation

Step 1: Read the String

  • The Scanner class is used to read a string input from the user. The nextLine() method captures the entire line as a string.

Step 2: Remove All Whitespace

  • The replaceAll() method is used with the regular expression \\s to match all whitespace characters (spaces, tabs, newlines, etc.) and replace them with an empty string "".

Step 3: Display the Result

  • The program prints the string without any whitespace using System.out.println().

Output Example

Example:

Enter a string: Java programming is fun String without whitespace: Javaprogrammingisfun 

Conclusion

This Java program demonstrates how to remove all whitespace from a user-input string. It covers essential concepts such as string manipulation, using regular expressions, and the replaceAll() method, making it a valuable exercise for beginners learning Java programming.

Leave a Comment

Scroll to Top