Grails Cookbook - A collection of tutorials and examples

Groovy String drop()

Groovy is one of the most fun language I ever tried to use. Maybe Ruby is equally fun but I have never tried it. Because I came from the Java line of programming, Groovy is more natural to me because it is the superset of Java and I get the chance to use any third party Java library inside Groovy. How fun is that? In this post we discuss another convenience method from String class. We will show how to use Groovy String drop method.

String drop Syntax

We take the documentation in this page and we get below syntax. The drop seqence is a method we can use in String class.
public static CharSequence drop(CharSequence self, int num)
We can shorten the syntax above to the one below as we don't really pass self when invoking the method.
public static CharSequence drop(int num)

And below is the official example from the documentation.

def text = "Groovy"
assert text.drop( 0 ) == 'Groovy'
assert text.drop( 2 ) == 'oovy'
assert text.drop( 7 ) == ''

And the method is described as drops the given number of chars from the head of this CharSequence if they are available. So what this method does is to return a CharSequence consisting of all characters except the first num ones, or else an empty String, if this CharSequence has less than num characters.

String drop Usage

Below is another example that we will wish to analyze:

def text = "James"
println text.drop( 2 )

So we are removing the first two characters from James, which are Ja. So when we remove Ja from James, we get the output below

mes

Another example

def text = "James"
println text.drop( 4 )

When we remove the first four characters, which will actually remove Jame, we get below output

s

If we pass parameter equal to the number of characters, for example
def text = "James"
println text.drop( 5 )
We get empty String. And even if we pass a parameter greater than the length of the String
def text = "James"
println text.drop( 15 )
We still get empty String.