In this section, you will learn how to remove all white spaces from the given string by using the regular expressions. This section gives you a example for the best illustration about the way of removing all the duplicate white spaces from the given string.
This program takes string from which all duplicate white spaces are removed if any exists in the string. And program shows the final string devoid of duplicate white spaces if any.
Pattern pattern = Pattern.compile("\\s+"):
Above code creates an instance of the Pattern class which compiles the text or regular expression i.e. used to search in the specified string.
Matcher matcher = pattern.matcher(string):
Above code creates an instance of the Matcher class which is used to match the compiled string in the string which is passed through the matcher() method of the above created instance of the Pattern class.
The find() method of the instance of Matcher class is used to check whether the compiled string matches in the specified string or not. This method returns the boolean value either true or false. If the text find in the string then the find() method returns the true value otherwise it returns the false value.
This method returns the whole string after replacing all duplicate white spaces by the single space and then it make a fresh string and return the whole string.
Here is the code of the program:
If you enjoyed this post then why not add us on Google+? Add us to your Circles
Liked it! Share this Tutorial
Ask Questions? Discuss: Removing duplicate white spaces from a String
Post your Comment