Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
"Write a method which will remove any given character from a String"
// "Write a method which will remove any given character from a String"
// The method will be the 'minus' method 'some string ' - 's' == 'ome tring'
def check() {
assert 'some string' - 's' == 'ome tring'
assert '' - 'a' == ''
assert 'something else' - 'z' == 'something else'
}
// Easy one
String.metaClass.minus { String c -> // careful, String already has a 'minus' method, if we override the one in CharSequence, it won't work
delegate.replaceAll(c, '')
}
check()
// Non-cheating one
String.metaClass.minus { String toRemove ->
StringBuffer buff = ''<<''
delegate.each { c ->
if (c != toRemove) buff << c
}
buff as String
}
check()​
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.