In this tutorial, you will learn how to write a java program to remove all the whitespaces from a string. To do that we are using replaceAll() method and inside which we are using regex to replace all white spaces with blank.
Java Program to remove all the white spaces from a string
In this example, we have a string str
and this string contain whitespaces. We are using replaceAll() method to replace the whitespaces in the existing string with the blanks. This will remove the whitespaces from the given string.
public class JavaExample {
public static void main(String[] args) {
String str="Hi, Welcome to BeginnersBook.com";
System.out.println("Original String:" + str);
//Using regex inside replaceAll() method to replace space with blank
str = str.replaceAll("\\s+", "");
System.out.println("String after white spaces are removed:" + str);
}
}
Output:
Example 2: Program to remove whitespace from user input string
This example is same as the above example except that the string here is not hardcoded and is entered by the user.
import java.util.Scanner;
public class JavaExample {
public static void main(String[] args) {
String str;
System.out.println("Enter any String: ");
Scanner sc = new Scanner(System.in);
str = sc.nextLine();
System.out.println("Original String: " + str);
//replacing white spaces space with blank
str = str.replaceAll("\\s+", "");
System.out.println("String after white spaces are removed: " + str);
}
}
Output: