Groovy adds a lot of methods to the Java String
class. For example we can use the take
method to get a certain number of characters from the start of a string value. With the drop
method we remove a given number of characters from the start of the string. In Groovy 3 we can now also take and drop a certain number of characters from the end of a string using the methods takeRight
and dropRight
.
In the following example we see how we can use the methods:
1 2 3 4 5 6 7 8 9 10 11 12 13 | def s = "Groovy rocks!" // Drop first 7 characters. assert s.drop( 7 ) == "rocks!" // Drop last 7 characters. assert s.dropRight( 7 ) == "Groovy" // Take first 6 characters. assert s.take( 6 ) == "Groovy" // Take last 6 characters. assert s.takeRight( 6 ) == "rocks!" |
Written with Groovy 3.0.2.