Remove Whitespace
Remove all whitespace characters from a string.
BeginnerTopic: Module 4: String Programs
Java Remove Whitespace Program
This program helps you to learn the fundamental structure and syntax of Java programming.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String s = sc.nextLine();
String noSpace = s.replaceAll("\\s+", "");
System.out.println("Without whitespace: " + noSpace);
sc.close();
}
}Output
Enter a string: a b c Without whitespace: abc
Understanding Remove Whitespace
We use a regex \\s+ to match all whitespace and replace with empty string.
Note: To write and run Java programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Java Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Java programs.