Jay Taylor's notes

back to listing index

Groovy String Tutorial - Grails Cookbook

[web search]
Original source (grails.asia)
Tags: jvm documentation groovy grails.asia
Clipped on: 2016-03-14

Image (Asset 1/5) alt=

If you like my posts, like my Facebook page please :)

Groovy String Tutorial

May 28, 2014 Groovy, Tutorial 1 comments

In any programming language, Strings and String manipulations are very important. This tutorial will show how cool it is to work with String using Groovy!
If you don't know how to setup an IDE and create a Groovy project, check out my post here and here.

Basics

Strings can either be defined using single or double quotes. The two objects below are Strings:

def firstName = 'John'
def lastName = "Doe"

And since Groovy is superset of Java, you can use String methods you normally use in Java:

println 'ABCDEF'.length()		// output: 6
println 'ABCDEF'.substring(1)		// output: BCDEF
println 'ABCDEF'.indexOf('C')		// output: 2
println 'ABCDEF'.replace('CD', 'XX')	// output: ABXXEF
println 'ABCDEF'.toLowerCase()		// output: abcdef

Concatenation is same as Java with the + sign.

def a = 'John'
println "Hello " + a + " and welcome"	// output: Hello John and welcome

Strings in double quote are called GStrings. A special property of it is it evaluates expressions inside it, enclosed in ${}. For example:

def firstName = 'John'
def lastName = "Doe"
println '${lastName}, ${firstName}'   // output: ${lastName}, ${firstName}
println "${lastName}, ${firstName}"   // output: Doe, John

Notice that the first line was taken literally, because it's just a normal String. The next line was evaluated because it's a GString.

Operators


Aside from + operator, - and * can be used:
println 'ABC' - 'B'   // output: A
println 'ABBC' - 'B'  // output: ABC
println 'ABBC' - 'BB' // output: AC
println 'ABC' * 2     // output: ABCABC
println 'ABC' * 3     // output: ABCABCABC

Escape

Backslash is used to escape special characters

println 'Hello\tWorld'	// output: Hello	World
println 'Hi\\There'	// output: Hi\There
println 'Hi\'There'	// output: Hi'There
println "Hi\"There"	// output: Hi"There

Multiple lines

You can initialize the value of a string with multiple lines, by using either backslash at the end of each line, or enclosing between triple quotes/double-quotes. Here are the different examples and their output:

def str1 = """#1 Hello 
This is a multi line
string example
"""
println str1
 
def str2 = '''#2
This is
Another multi line
string sammple
'''
println str2
 
def str3 = '#3 This is\
a sample with\
backslash'
println str3
 
def str4 = '\n#4 Another example\n\
with backslash\n\
and next line'
println str4

This is the output of the code above:

#1 Hello 
This is a multi line
string example
 
#2
This is
Another multi line
string sammple
 
#3 This isa sample withbackslash
 
#4 Another example
with backslash
and next line

Padding

Groovy supports padding to make sure a String is of a particular length. For example:

def str = 'ABC'.padLeft(5)
println str
println str.length()

Will output:

  ABC
5
Notice that the string is padded with 2 blank spaces to the left, to make sure it is 5 characters.

It is also possible to specify the text to pad, if you wish not to use space.

println 'ABC'.padLeft(5,'+') // output: ++ABC

You are not limited to padding a certain character to a String. You can also choose to pad a string. For example:

println 'ABC'.padLeft(10,'123') // output: 1231231ABC
The string "123" are repeated until the required 10 characters is met.
You can pad to the left, right, or center the original string. For example:
println 'ABC'.padLeft(8,'+')  // output: +++++ABC
println 'ABC'.padRight(8,'+') // output: ABC+++++
println 'ABC'.center(8,'+')   // output: ++ABC+++

Tokenize


Tokenizing a string is more convenient in Groovy. For example:
def list1 = 'i am john'.tokenize()
Is the same as:
def list1 = ['i', 'am', 'john']
By default, it will be tokenized by white spaces (space, tab, next line).

It is possible to tokenize using a specific delimiter:

def a = 'i,am,john'.tokenize()     // same as: ['i,am,john']
def b = 'i,am-john'.tokenize(',-') // same as: ['i', 'am', 'john']

Closure

Strings can be manipulated using closures.

find will iterate through each character and will return the first character that matches the criteria given. findAll on the other hand, will return all characters that matches the criteria as list. Example:

println 'grails'.find{ it > 'i' }     // output: r
println 'grails'.findAll{ it > 'i' }  // output: [r, l, s]
println 'grails'.findAll{ it >= 's' } // output: [s]

every will test each character and will return true if all matches the criteria. These 2 conditions are identical:

def a = 'abc'.every{ it > 'b' }
def b = 'abc'[0] > 'b' && 'abc'[1] > 'b' && 'abc'[2] > 'b' 

any will test each character and will return true if one of them matches the criteria. These 2 conditions are identical:

def a = 'abc'.any{ it > 'b' }
def b = 'abc'[0] > 'b' || 'abc'[1] > 'b' || 'abc'[2] > 'b' 

collect will construct a new list by manipulating each character.

'abc'.collect{ it }            // ['a', 'b', 'c']
'abc'.collect{ it + '.' }      // ['a.', 'b.', 'c.']
'abc'.collect{ 'test-' + it  } // ['test-a', 'test-b', 'test-c']
'abc'.collect{ it * 3 }        // ['aaa', 'bbb', 'ccc']


Other Groovy Tutorials


Grails Project Themes

Image (Asset 2/5) alt= Image (Asset 3/5) alt= Image (Asset 4/5) alt=

Snippet

Groovy