Algorithm
-
Input String: Take the input string that contains whitespaces.
-
Remove Whitespace Method: Create a method (
removeWhitespaces
) that takes a string as input and uses thereplaceAll
method with the regular expression\\s
to replace all whitespaces with an empty string. -
Display Result: Display the original string and the modified string without whitespaces.
Code Examples
#1 Code Example- Java Program to Remove All Whitespaces
Code -
Java Programming
public class Whitespaces {
public static void main(String[] args) {
String sentence = "T his is b ett er.";
System.out.println("Original sentence: " + sentence);
sentence = sentence.replaceAll("\\s", "");
System.out.println("After replacement: " + sentence);
}
}
Copy The Code &
Try With Live Editor
Output
After replacement: Thisisbetter.
#2 Code Example-Take string from users and remove the white space
Code -
Java Programming
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// create an object of Scanner
Scanner sc = new Scanner(System.in);
System.out.println("Enter the string");
// take the input
String input = sc.nextLine();
System.out.println("Original String: " + input);
// remove white spaces
input = input.replaceAll("\\s", "");
System.out.println("Final String: " + input);
sc.close();
}
}
Copy The Code &
Try With Live Editor
Output
J av a- P rog ram m ing
Original String: J av a- P rog ram m ing
Final String: Java-Programming
Demonstration
Java Programing Example to Remove All Whitespaces from a String-DevsEnv