Remove Whitespace in Java
Remove all whitespace characters from a string.
BeginnerModule 4: String ProgramsExample 6 of 25
remove-whitespace.java
1import java.util.Scanner;23public class Main {4 public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);6 System.out.print("Enter a string: ");7 String s = sc.nextLine();89 String noSpace = s.replaceAll("\\s+", "");10 System.out.println("Without whitespace: " + noSpace);11 sc.close();12 }13}
Output
Enter a string: a b c Without whitespace: abc
What's going on
We use a regex \\s+ to match all whitespace and replace with empty string.