I have a string like
String str = "My name is Monda"
How can I achieve a string like
str = "MynameisMonda"
The replaceAll() method of the String class replaces each substring of this string that matches the given regular expression with the given replacement. You can remove white spaces from a string by replacing " " with "".
The Groovy community has added a take() method which can be used for easy and safe string truncation. Both take() and drop() are relative to the start of the string, as in "take from the front" and "drop from the front". Show activity on this post. In Groovy, strings can be considered as ranges of characters.
Groovy has added the minus() method to the String class. And because the minus() method is used by the - operator we can remove parts of a String with this operator. The argument can be a String or a regular expression Pattern. The first occurrence of the String or Pattern is then removed from the original String.
replaceAll() Method. Just like replaceFirst(), the replaceAll() also accepts a regular expression and given replacement. It replaces each substring that matches the given criteria. To remove a prefix, we can use this method too.
You can use the replaceAll()
function.
For your case:
replaceAll("\\s","")
where \s
means any whitespace (such as a space character).
You just need this function. replaceAll()
str.replaceAll("\\s","")
\s
= Anything that is a space character (including space, tab characters etc)
You need to escape the backslash if you want \s to reach the regex engine, resulting in \s. Like wise we use :-
\S
= Anything that isn't a space character (including both letters and numbers, as well as punctuation etc)
\w
= Anything that is a word character
\W
= Anything that isn't a word character (including punctuation etc)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With