Created
January 8, 2016 11:46
-
-
Save aesteve/95a3cc56e061b50357c7 to your computer and use it in GitHub Desktop.
"Write a method which will remove any given character from a String"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// "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