If you need to remove spaces between words in a String in Java then there are the following two options-
- Using
replaceAll()
method of the Java String class. - Using
StringUtils.normalizeSpace()
method that requires Apache Commons Lang.
Remove spaces between words using replaceAll() method
- replaceAll(String regex, String replacement)- Replaces each substring of this string that matches the given regular expression with the given replacement.
Here "\\s+" is passed as regular expression that matches any number of whitespaces and single space (" ") is passed as replacement string to replace matched spaces with a single space.
public class StringSpaceRemoval { public static void main(String[] args) { String str = " Example String "; // regex to match any number of spaces str = str.replaceAll("\\s+", " "); System.out.println(str); } }
Output
Example String
Here leading and trailing spaces are also replaced with a single space. You may want to completely remove any leading and trailing spaces and normalize the spaces in between the words for that you can use trim() method along with replaceAll().
public class StringSpaceRemoval { public static void main(String[] args) { String str = " Example String "; // regex to match any number of spaces str = str.trim().replaceAll("\\s+", " "); System.out.println(str); } }
Output
Example String
Remove spaces between words using StringUtils.normalizeSpace()
Use of this method requires commons-lang jar, Maven dependency for that is as given below-
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.9</version> </dependency>
StringUtils.normalizeSpace() method takes care of removing any leading and trailing spaces and normalizes the spaces between the words.
import org.apache.commons.lang3.StringUtils; public class StringSpaceRemoval { public static void main(String[] args) { String str = " Example String "; str = StringUtils.normalizeSpace(str); System.out.println(str); } }
Output
Example String
That's all for this topic Removing Spaces Between Words in a String Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Java Programs Page
Related Topics
You may also like-
No comments:
Post a Comment