Java Program to Remove All Spaces From Given String

Java Programming Examples

Java String Programs

This Java program removes spaces from the string entered by the user. It checks for and removes all blank characters using a regular expression and prints the final output to the screen.



Example Java Program:
import java.util.Scanner;

public class RemoveSpaces {

    public static void main(String[] args) {
        Scanner obj = new Scanner(System.in); /* create a object */

        /* Taking user input */
        System.out.print("Enter some text: ");
        String sentence = obj.nextLine();

        /* Check and remove all spaces. */
        sentence = sentence.replaceAll("\\s", "");
        System.out.println("Text after removing spaces: " + sentence);
    }
}

Program Output:

Enter some text: W3 S c h o o l s
Text after removing spaces: W3Schools


Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram

Keep W3schools Growing with Your Support!
❤️ Support W3schools