Remove All Spaces in Java: Explanation & Practice
Remove all whitespace from a string
Problem summary
Write a program that removes all spaces from a string.
Starter code
public class Main {
public static void main(String[] args) {
String text = "H e l l o W o r l d"; // Test case 1
// Remove all spaces
// Print result
}
}Expected output and test cases
- Remove all spaces
HelloWorld
- Multiple spaces removed
JavaProgramming
- Already no spaces
NoSpaces
Hints
- Use .replace(" ", "")
- Or .replaceAll("\\s", "")
- Loop and skip space characters
Related Strings exercises
Practice all Strings exercises · Run this idea in the Java compiler