Remove All Whitespaces from a String in Java
Removing whitespaces from a string means eliminating all space characters (including spaces, tabs, and new lines) and keeping only the actual content.
This operation is commonly used in input validation, data cleaning, and preprocessing user-entered text.
How the Logic Works
- Read the input string.
- Convert the string into a character array.
- Traverse each character one by one.
- If the character is not a whitespace, add it to the result.
Example 1
Input: "Java Programming"
Output: JavaProgramming
Example 2
Input: " Learn Java Fast "
Output: LearnJavaFast
Java Program to Remove All Whitespaces
import java.util.Scanner;
public class RemoveWhitespaces {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = sc.nextLine();
String result = "";
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch != ' ' && ch != '\t' && ch != '\n') {
result = result + ch;
}
}
System.out.println("String without whitespaces: " + result);
}
}
Sample Output
Enter a string: Java is awesome
String without whitespaces: Javaisawesome
Important Notes
- All types of whitespace characters are removed.
- No
replace()or regular expressions are used. - Demonstrates character-level string processing.
Practice Challenges
- Modify the program to remove only extra spaces between words.
- Count how many whitespaces were removed.
- Rewrite the program using
StringBuilderfor better performance.
This program is a great exercise to understand how strings work internally and how to process user input efficiently in Java.