To remove spaces from a string in Java, use the
replaceAll
method with \\s+
regular expression pattern.Here's how you do it:
String string = " Hello World ! ";
String noSpaces = string.replaceAll("\\s+", "");
System.out.println(noSpaces); // HelloWorld!