Suppose I would like to remove all "
surrounding a string. In Python, I would:
>>> s='"Don\'t need the quotes"'
>>> print s
"Don't need the quotes"
>>> print s.strip('"')
Don't need the quotes
And if I want to remove multiple characters, e.g. "
and parentheses:
>> s='"(Don\'t need quotes and parens)"'
>>> print s
"(Don't need quotes and parens)"
>>> print s.strip('"()')
Don't need quotes and parens
What's the elegant way to strip a string in Java?
strip() is an instance method that returns a string whose value is the string with all leading and trailing white spaces removed. This method was introduced in Java 11. If the string contains only white spaces, then applying this method will result in an empty string.
To remove leading and trailing spaces in Java, use the trim() method. This method returns a copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space.
The Strip() method in Python removes or truncates the given characters from the beginning and the end of the original string. The default behavior of the strip() method is to remove the whitespace from the beginning and at the end of the string.
The set interface is present in java. util package and extends the Collection interface. It is an unordered collection of objects in which duplicate values cannot be stored.
Suppose I would like to remove all
"
surrounding a string
The closest equivalent to the Python code is:
s = s.replaceAll("^\"+", "").replaceAll("\"+$", "");
And if I want to remove multiple characters, e.g.
"
and parentheses:
s = s.replaceAll("^[\"()]+", "").replaceAll("[\"()]+$", "");
If you can use Apache Commons Lang, there's StringUtils.strip()
.
The Guava library has a handy utility for it. The library contains CharMatcher.trimFrom()
, which does what you want. You just need to create a CharMatcher
which matches the characters you want to remove.
Code:
CharMatcher matcher = CharMatcher.is('"');
System.out.println(matcher.trimFrom(s));
CharMatcher matcher2 = CharMatcher.anyOf("\"()");
System.out.println(matcher2.trimFrom(s));
Internally, this does not create any new String, but just calls s.subSequence()
. As it also doesn't need Regexps, I guess its the fastest solution (and surely the cleanest and easiest to understand).
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