This Java tutorial shows how to remove spaces from a string in Java.
If you only have spaces at the beginning or end of the String, you can use the trim() method. This method will remove whitespace from the beginning and end of the String, but not if it the spaces are within the String. Below is an example of using the trim() method.
String trailingSpaces = " word ";
String noSpaces = trailingSpaces.trim();
To remove all spaces in a String, you can use the replaceAll() method. The method allows you to replace all occurrences of a String with another String. To remove all strings, we will replace a space " " with an empty string "".
String spaces = "This is a test";
String noSpaces = spaces.replaceAll(" ", "");
This variable noSpace will be "Thisisatest".
0 comments:
Post a Comment