Grails Cookbook - A collection of tutorials and examples

Groovy String take()

The Groovy language provides many convenience method to do cool stuff, specially on String manipulation. In this post, we will check a special way to have a substring of a string using the Take method. We will explore some samples on how to use Groovy String Take method.


When we check the documentation, below is the syntax for String take method in the Groovy language.

public static CharSequence take(CharSequence self, int num)

Since the char sequence is itself, then there is only one parameter which is the number num. And this is the official example from the documentation:
def text = "Groovy"
 assert text.take( 0 ) == ''
 assert text.take( 2 ) == 'Gr'
 assert text.take( 7 ) == 'Groovy'

Relation to Substring()

Essentially, a call to take method like below
Is almost equivalent to

What this mean is the Groovy String take method takes the first n characters of the String and return it to the caller. For example:

def myString = "HelloWorld"
println myString.take(3)
println myString.take(5)
println myString.take(7)

The output is below.


The code we show above is equivalent to:

def myString = "HelloWorld"
println myString.substring(0,3)
println myString.substring(0,5)
println myString.substring(0,7)

But what if we use a big index greater than the length of the String? This code:
println "ABC".take(5)

Will output


But if we use substring

println "ABC".take.substring(0,5)

Will result to an exception.